@metamask-previews/marketing-consent-controller 0.0.0-stage → 1.0.0-preview-686aaf7

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 ADDED
@@ -0,0 +1,20 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [1.0.0]
11
+
12
+ ### Added
13
+
14
+ - Initial release ([#10821](https://github.com/MetaMask/core/pull/10821))
15
+ - Add `MarketingConsentController`, which keeps marketing consent in sync with Authenticated User Storage and turns off marketing notification channels before an opt-out is saved
16
+ - Add `initialize` method, which reads the controllers it depends on and starts syncing; call it once they are registered
17
+ - Add `setMarketingConsent` method and `MarketingConsentController:setMarketingConsent` action, which apply a consent change, wait until Authenticated User Storage saves it; if the save fails, the change is dropped and consent is re-read from Authenticated User Storage, the source of truth
18
+
19
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/marketing-consent-controller@1.0.0...HEAD
20
+ [1.0.0]: https://github.com/MetaMask/core/releases/tag/@metamask/marketing-consent-controller@1.0.0
package/LICENSE ADDED
@@ -0,0 +1,6 @@
1
+ This project is licensed under either of
2
+
3
+ * MIT license ([LICENSE.MIT](LICENSE.MIT))
4
+ * Apache License, Version 2.0 ([LICENSE.APACHE2](LICENSE.APACHE2))
5
+
6
+ at your option.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 MetaMask
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/LICENSE.MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MetaMask
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,69 @@
1
- # Temporary Holding Version
1
+ # `@metamask/marketing-consent-controller`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Keeps marketing consent in sync with Authenticated User Storage
4
+
5
+ ## Installation
6
+
7
+ `yarn add @metamask/marketing-consent-controller`
8
+
9
+ or
10
+
11
+ `npm install @metamask/marketing-consent-controller`
12
+
13
+ ## Usage
14
+
15
+ `MarketingConsentController` keeps the user's marketing consent, held locally by `AnalyticsController`, in sync with their Authenticated User Storage (AUS) profile. AUS is the source of truth.
16
+
17
+ ### Setup
18
+
19
+ Construct it, then call `initialize()` once `AnalyticsController`, `AuthenticationController` and `KeyringController` are registered. The constructor doesn't call other controllers; `initialize()` reads their state, subscribes to their changes and starts syncing.
20
+
21
+ ```ts
22
+ const controller = new MarketingConsentController({
23
+ messenger,
24
+ state, // persisted state, if any
25
+ clientType: 'extension', // or 'mobile'
26
+ });
27
+
28
+ // After every controller is registered:
29
+ controller.initialize();
30
+ ```
31
+
32
+ Before `initialize()`, the controller doesn't sync: `setMarketingConsent` applies the choice locally and saves it once `initialize()` has run and the user is signed in.
33
+
34
+ The messenger must allow these actions and events:
35
+
36
+ - Actions:
37
+ - `AuthenticatedUserStorageService:invalidateQueries`, `getMarketingConsent`, `putMarketingConsent`, `getNotificationPreferences`, `putNotificationPreferences`
38
+ - `AnalyticsController:getState`, `optInToMarketing`, `optOutOfMarketing`
39
+ - `AuthenticationController:getState`
40
+ - `KeyringController:getState`
41
+ - Events:
42
+ - `AnalyticsController:stateChanged` and `AuthenticationController:stateChanged` (not the deprecated `stateChange`)
43
+ - `KeyringController:lock`, `KeyringController:unlock`
44
+
45
+ ### Changing consent
46
+
47
+ Call `MarketingConsentController:setMarketingConsent(enabled)` for every user choice.
48
+
49
+ - It resolves once AUS has saved the change.
50
+ - Turning consent off also turns off the AUS marketing notification channels.
51
+ - Before sign-in finishes (for example during onboarding), the change is applied locally and saved once the wallet is unlocked and signed in; the call resolves without waiting. A change still unsaved when the wallet locks is saved after the next unlock and sign-in.
52
+ - If AUS does not save the change, the call rejects and local consent is re-read from AUS.
53
+ - If a newer choice is made while it waits (another call, or other code changing consent in `AnalyticsController`), the call resolves without an error; the newer choice is saved on its own.
54
+
55
+ ### Re-reading AUS
56
+
57
+ Call `MarketingConsentController:refresh()` when the wallet UI opens or the app returns to the foreground. It also retries a change whose save failed. The controller re-reads AUS by itself on sign-in and unlock.
58
+
59
+ ### Notification preferences
60
+
61
+ To turn a marketing notification channel on, save consent first, then turn the channel on through `NotificationServicesController:updateNotificationPreferences`. That method rejects updates that turn a marketing channel on without consent, with an error whose `code` is `MARKETING_CONSENT_REQUIRED_ERROR_CODE` (exported by `@metamask/notification-services-controller`).
62
+
63
+ ## Architecture
64
+
65
+ See [ARCHITECTURE.md](./ARCHITECTURE.md) for how the controller syncs consent with AUS.
66
+
67
+ ## Contributing
68
+
69
+ This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme).
@@ -0,0 +1,40 @@
1
+ /**
2
+ * This file is auto generated.
3
+ * Do not edit manually.
4
+ */
5
+ import type { MarketingConsentController } from './MarketingConsentController.js';
6
+ /**
7
+ * Sets the user's marketing consent and saves it to AUS.
8
+ *
9
+ * Turning consent off also turns off the AUS marketing notification
10
+ * channels, before consent is saved.
11
+ *
12
+ * Before sign-in finishes (e.g. during onboarding), the change is applied
13
+ * locally and saved to AUS once the wallet is unlocked and signed in; the
14
+ * call resolves without waiting for that.
15
+ *
16
+ * A call overtaken by a newer choice (a newer call, or other code changing
17
+ * consent in AnalyticsController) resolves without waiting; the newer
18
+ * choice is saved on its own.
19
+ *
20
+ * @param enabled - Whether the user consents to marketing.
21
+ * @throws If AUS did not save the change. AUS is the source of truth, so
22
+ * the change is then dropped and local consent is re-read from AUS.
23
+ */
24
+ export type MarketingConsentControllerSetMarketingConsentAction = {
25
+ type: `MarketingConsentController:setMarketingConsent`;
26
+ handler: MarketingConsentController['setMarketingConsent'];
27
+ };
28
+ /**
29
+ * Re-reads consent from AUS, e.g. when the wallet UI opens or the app
30
+ * returns to the foreground.
31
+ */
32
+ export type MarketingConsentControllerRefreshAction = {
33
+ type: `MarketingConsentController:refresh`;
34
+ handler: MarketingConsentController['refresh'];
35
+ };
36
+ /**
37
+ * Union of all MarketingConsentController action types.
38
+ */
39
+ export type MarketingConsentControllerMethodActions = MarketingConsentControllerSetMarketingConsentAction | MarketingConsentControllerRefreshAction;
40
+ //# sourceMappingURL=MarketingConsentController-method-action-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MarketingConsentController-method-action-types.d.ts","sourceRoot":"","sources":["../src/MarketingConsentController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,iCAAiC,CAAC;AAElF;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,MAAM,mDAAmD,GAAG;IAChE,IAAI,EAAE,gDAAgD,CAAC;IACvD,OAAO,EAAE,0BAA0B,CAAC,qBAAqB,CAAC,CAAC;CAC5D,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,uCAAuC,GAAG;IACpD,IAAI,EAAE,oCAAoC,CAAC;IAC3C,OAAO,EAAE,0BAA0B,CAAC,SAAS,CAAC,CAAC;CAChD,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,uCAAuC,GAC/C,mDAAmD,GACnD,uCAAuC,CAAC"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * This file is auto generated.
3
+ * Do not edit manually.
4
+ */
5
+ export {};
6
+ //# sourceMappingURL=MarketingConsentController-method-action-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MarketingConsentController-method-action-types.js","sourceRoot":"","sources":["../src/MarketingConsentController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { MarketingConsentController } from './MarketingConsentController.js';\n\n/**\n * Sets the user's marketing consent and saves it to AUS.\n *\n * Turning consent off also turns off the AUS marketing notification\n * channels, before consent is saved.\n *\n * Before sign-in finishes (e.g. during onboarding), the change is applied\n * locally and saved to AUS once the wallet is unlocked and signed in; the\n * call resolves without waiting for that.\n *\n * A call overtaken by a newer choice (a newer call, or other code changing\n * consent in AnalyticsController) resolves without waiting; the newer\n * choice is saved on its own.\n *\n * @param enabled - Whether the user consents to marketing.\n * @throws If AUS did not save the change. AUS is the source of truth, so\n * the change is then dropped and local consent is re-read from AUS.\n */\nexport type MarketingConsentControllerSetMarketingConsentAction = {\n type: `MarketingConsentController:setMarketingConsent`;\n handler: MarketingConsentController['setMarketingConsent'];\n};\n\n/**\n * Re-reads consent from AUS, e.g. when the wallet UI opens or the app\n * returns to the foreground.\n */\nexport type MarketingConsentControllerRefreshAction = {\n type: `MarketingConsentController:refresh`;\n handler: MarketingConsentController['refresh'];\n};\n\n/**\n * Union of all MarketingConsentController action types.\n */\nexport type MarketingConsentControllerMethodActions =\n | MarketingConsentControllerSetMarketingConsentAction\n | MarketingConsentControllerRefreshAction;\n"]}
@@ -0,0 +1,133 @@
1
+ import type { AnalyticsControllerGetStateAction, AnalyticsControllerOptInToMarketingAction, AnalyticsControllerOptOutOfMarketingAction, AnalyticsControllerState } from '@metamask/analytics-controller';
2
+ import type { AuthenticatedUserStorageInvalidateQueriesAction, AuthenticatedUserStorageServiceGetMarketingConsentAction, AuthenticatedUserStorageServiceGetNotificationPreferencesAction, AuthenticatedUserStorageServicePutMarketingConsentAction, AuthenticatedUserStorageServicePutNotificationPreferencesAction, ClientType } from '@metamask/authenticated-user-storage';
3
+ import { BaseController } from '@metamask/base-controller';
4
+ import type { ControllerGetStateAction, ControllerStateChangedEvent } from '@metamask/base-controller';
5
+ import type { KeyringControllerGetStateAction, KeyringControllerLockEvent, KeyringControllerUnlockEvent } from '@metamask/keyring-controller';
6
+ import type { Messenger } from '@metamask/messenger';
7
+ import type { AuthenticationController } from '@metamask/profile-sync-controller';
8
+ import type { MarketingConsentControllerMethodActions } from './MarketingConsentController-method-action-types.js';
9
+ /**
10
+ * The name of the {@link MarketingConsentController}, used to namespace the
11
+ * controller's actions and events and to namespace the controller's state data
12
+ * when composed with other controllers.
13
+ */
14
+ declare const controllerName = "MarketingConsentController";
15
+ /** State managed by MarketingConsentController. */
16
+ export type MarketingConsentControllerState = {
17
+ /**
18
+ * A local consent change not yet written to Authenticated User Storage, or
19
+ * `null` when there is none. Persisted so the change survives a restart and
20
+ * is written to whichever profile signs in next.
21
+ */
22
+ pendingMarketingConsent: boolean | null;
23
+ };
24
+ /**
25
+ * Returns the default state for MarketingConsentController.
26
+ *
27
+ * @returns The default state.
28
+ */
29
+ export declare function getDefaultMarketingConsentControllerState(): MarketingConsentControllerState;
30
+ /**
31
+ * Retrieves the state of the {@link MarketingConsentController}.
32
+ */
33
+ export type MarketingConsentControllerGetStateAction = ControllerGetStateAction<typeof controllerName, MarketingConsentControllerState>;
34
+ /**
35
+ * Actions that {@link MarketingConsentControllerMessenger} exposes to other
36
+ * consumers.
37
+ */
38
+ export type MarketingConsentControllerActions = MarketingConsentControllerGetStateAction | MarketingConsentControllerMethodActions;
39
+ /**
40
+ * Published when the state of {@link MarketingConsentController} changes.
41
+ */
42
+ export type MarketingConsentControllerStateChangedEvent = ControllerStateChangedEvent<typeof controllerName, MarketingConsentControllerState>;
43
+ /**
44
+ * Events that {@link MarketingConsentControllerMessenger} exposes to other
45
+ * consumers.
46
+ */
47
+ export type MarketingConsentControllerEvents = MarketingConsentControllerStateChangedEvent;
48
+ type AuthenticationControllerState = AuthenticationController.AuthenticationControllerState;
49
+ /**
50
+ * Actions from other messengers that {@link MarketingConsentControllerMessenger}
51
+ * calls.
52
+ */
53
+ type AllowedActions = AuthenticatedUserStorageInvalidateQueriesAction | AuthenticatedUserStorageServiceGetMarketingConsentAction | AuthenticatedUserStorageServicePutMarketingConsentAction | AuthenticatedUserStorageServiceGetNotificationPreferencesAction | AuthenticatedUserStorageServicePutNotificationPreferencesAction | AnalyticsControllerGetStateAction | AnalyticsControllerOptInToMarketingAction | AnalyticsControllerOptOutOfMarketingAction | AuthenticationController.AuthenticationControllerGetStateAction | KeyringControllerGetStateAction;
54
+ /**
55
+ * Events from other messengers that {@link MarketingConsentControllerMessenger}
56
+ * subscribes to.
57
+ */
58
+ type AllowedEvents = ControllerStateChangedEvent<'AnalyticsController', AnalyticsControllerState> | ControllerStateChangedEvent<'AuthenticationController', AuthenticationControllerState> | KeyringControllerLockEvent | KeyringControllerUnlockEvent;
59
+ /**
60
+ * The messenger restricted to actions and events accessed by
61
+ * {@link MarketingConsentController}.
62
+ */
63
+ export type MarketingConsentControllerMessenger = Messenger<typeof controllerName, MarketingConsentControllerActions | AllowedActions, MarketingConsentControllerEvents | AllowedEvents>;
64
+ /**
65
+ * Keeps the user's marketing consent (held locally by `AnalyticsController`)
66
+ * in sync with their Authenticated User Storage (AUS) profile. AUS is the
67
+ * source of truth.
68
+ *
69
+ * - Clients change consent with
70
+ * {@link MarketingConsentController.setMarketingConsent}, which resolves once
71
+ * AUS has saved the change.
72
+ * - On sign-in, unlock or {@link MarketingConsentController.refresh}, consent
73
+ * is read from AUS and applied locally.
74
+ * - A local change not yet saved (e.g. made during onboarding, before sign-in
75
+ * finishes) wins at the next sync and is written to AUS. If AUS has no record, the local value is
76
+ * written to it.
77
+ * - Whenever consent is off, the AUS "marketing" notification channels are
78
+ * turned off too, including when another client revoked consent.
79
+ */
80
+ export declare class MarketingConsentController extends BaseController<typeof controllerName, MarketingConsentControllerState, MarketingConsentControllerMessenger> {
81
+ #private;
82
+ /**
83
+ * Creates a new MarketingConsentController. It doesn't read other
84
+ * controllers or sync until {@link MarketingConsentController.initialize} is
85
+ * called.
86
+ *
87
+ * @param options - Constructor options.
88
+ * @param options.messenger - The messenger scoped to this controller.
89
+ * @param options.state - Initial state, merged with the defaults.
90
+ * @param options.clientType - The client writing to AUS.
91
+ */
92
+ constructor({ messenger, state, clientType, }: {
93
+ messenger: MarketingConsentControllerMessenger;
94
+ state?: Partial<MarketingConsentControllerState>;
95
+ clientType: ClientType;
96
+ });
97
+ /**
98
+ * Reads the lock, sign-in and consent state, subscribes to their changes
99
+ * and starts the first sync. Call it once every controller this one depends
100
+ * on is registered. Calling it again does nothing.
101
+ *
102
+ * It isn't named `init` because `Wallet` from `@metamask/wallet` calls
103
+ * `init` on its instances before `AnalyticsController` is registered. Once
104
+ * `AnalyticsController` is part of `@metamask/wallet`, `init` can call this.
105
+ */
106
+ initialize(): void;
107
+ /**
108
+ * Sets the user's marketing consent and saves it to AUS.
109
+ *
110
+ * Turning consent off also turns off the AUS marketing notification
111
+ * channels, before consent is saved.
112
+ *
113
+ * Before sign-in finishes (e.g. during onboarding), the change is applied
114
+ * locally and saved to AUS once the wallet is unlocked and signed in; the
115
+ * call resolves without waiting for that.
116
+ *
117
+ * A call overtaken by a newer choice (a newer call, or other code changing
118
+ * consent in AnalyticsController) resolves without waiting; the newer
119
+ * choice is saved on its own.
120
+ *
121
+ * @param enabled - Whether the user consents to marketing.
122
+ * @throws If AUS did not save the change. AUS is the source of truth, so
123
+ * the change is then dropped and local consent is re-read from AUS.
124
+ */
125
+ setMarketingConsent(enabled: boolean): Promise<void>;
126
+ /**
127
+ * Re-reads consent from AUS, e.g. when the wallet UI opens or the app
128
+ * returns to the foreground.
129
+ */
130
+ refresh(): void;
131
+ }
132
+ export {};
133
+ //# sourceMappingURL=MarketingConsentController.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MarketingConsentController.d.ts","sourceRoot":"","sources":["../src/MarketingConsentController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iCAAiC,EACjC,yCAAyC,EACzC,0CAA0C,EAC1C,wBAAwB,EACzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EACV,+CAA+C,EAC/C,wDAAwD,EACxD,+DAA+D,EAC/D,wDAAwD,EACxD,+DAA+D,EAC/D,UAAU,EACX,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,KAAK,EACV,wBAAwB,EACxB,2BAA2B,EAE5B,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EACV,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAC7B,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,mCAAmC,CAAC;AAElF,OAAO,KAAK,EAAE,uCAAuC,EAAE,MAAM,qDAAqD,CAAC;AAInH;;;;GAIG;AACH,QAAA,MAAM,cAAc,+BAA+B,CAAC;AA8CpD,mDAAmD;AACnD,MAAM,MAAM,+BAA+B,GAAG;IAC5C;;;;OAIG;IACH,uBAAuB,EAAE,OAAO,GAAG,IAAI,CAAC;CACzC,CAAC;AAcF;;;;GAIG;AACH,wBAAgB,yCAAyC,IAAI,+BAA+B,CAE3F;AASD;;GAEG;AACH,MAAM,MAAM,wCAA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AgBjB;IAED;;;;;;;;;;;;;;;;;OAiBG;IACG,mBAAmB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CA+BzD;IA+DD;;;OAGG;IACH,OAAO,IAAI,IAAI,CAGd;CA4VF"}
@@ -0,0 +1,529 @@
1
+ import { BaseController } from '@metamask/base-controller';
2
+ // === GENERAL ===
3
+ /**
4
+ * The name of the {@link MarketingConsentController}, used to namespace the
5
+ * controller's actions and events and to namespace the controller's state data
6
+ * when composed with other controllers.
7
+ */
8
+ const controllerName = 'MarketingConsentController';
9
+ /**
10
+ * Picks the marketing consent fields from AnalyticsController state.
11
+ *
12
+ * @param state - The AnalyticsController state.
13
+ * @returns The local marketing consent.
14
+ */
15
+ function toLocalConsent(state) {
16
+ return {
17
+ optedIn: state.optedInToMarketing === true,
18
+ decided: state.marketingConsentDecisionMade === true,
19
+ };
20
+ }
21
+ /**
22
+ * The metadata for each property in {@link MarketingConsentControllerState}.
23
+ */
24
+ const marketingConsentControllerMetadata = {
25
+ pendingMarketingConsent: {
26
+ includeInStateLogs: true,
27
+ persist: true,
28
+ includeInDebugSnapshot: true,
29
+ usedInUi: false,
30
+ },
31
+ };
32
+ /**
33
+ * Returns the default state for MarketingConsentController.
34
+ *
35
+ * @returns The default state.
36
+ */
37
+ export function getDefaultMarketingConsentControllerState() {
38
+ return { pendingMarketingConsent: null };
39
+ }
40
+ // === MESSENGER ===
41
+ /**
42
+ * The controller methods exposed as messenger actions.
43
+ */
44
+ const MESSENGER_EXPOSED_METHODS = ['setMarketingConsent', 'refresh'];
45
+ // === CONTROLLER DEFINITION ===
46
+ /**
47
+ * Keeps the user's marketing consent (held locally by `AnalyticsController`)
48
+ * in sync with their Authenticated User Storage (AUS) profile. AUS is the
49
+ * source of truth.
50
+ *
51
+ * - Clients change consent with
52
+ * {@link MarketingConsentController.setMarketingConsent}, which resolves once
53
+ * AUS has saved the change.
54
+ * - On sign-in, unlock or {@link MarketingConsentController.refresh}, consent
55
+ * is read from AUS and applied locally.
56
+ * - A local change not yet saved (e.g. made during onboarding, before sign-in
57
+ * finishes) wins at the next sync and is written to AUS. If AUS has no record, the local value is
58
+ * written to it.
59
+ * - Whenever consent is off, the AUS "marketing" notification channels are
60
+ * turned off too, including when another client revoked consent.
61
+ */
62
+ export class MarketingConsentController extends BaseController {
63
+ /**
64
+ * The client sent with every AUS write.
65
+ */
66
+ #clientType;
67
+ /**
68
+ * Whether {@link MarketingConsentController.initialize} has run.
69
+ */
70
+ #initialized = false;
71
+ /**
72
+ * Whether the wallet is unlocked, kept in step with the KeyringController
73
+ * lock and unlock events. Starts `false`, so nothing syncs before `initialize`.
74
+ */
75
+ #isUnlocked = false;
76
+ /**
77
+ * The last signed-in status seen, so a sign-in or sign-out can be told apart
78
+ * from other AuthenticationController changes.
79
+ */
80
+ #isSignedIn = false;
81
+ /**
82
+ * The last local consent seen, so the AnalyticsController listener can tell
83
+ * a first decision from a changed one. Read local consent with
84
+ * {@link MarketingConsentController.#getLocalConsent} instead.
85
+ */
86
+ #lastSeenConsent = { optedIn: false, decided: false };
87
+ /**
88
+ * The current signed-in session.
89
+ */
90
+ #session = {};
91
+ /**
92
+ * The AUS value being applied locally, so its state change is not taken for
93
+ * a local change.
94
+ */
95
+ #applyingRemoteValue;
96
+ /**
97
+ * The sync run in progress, if any. Only one runs at a time.
98
+ */
99
+ #inFlight;
100
+ /**
101
+ * Counts {@link MarketingConsentController.setMarketingConsent} calls, so a
102
+ * call overtaken by a newer one can tell.
103
+ */
104
+ #latestConsentRequest = 0;
105
+ /**
106
+ * Creates a new MarketingConsentController. It doesn't read other
107
+ * controllers or sync until {@link MarketingConsentController.initialize} is
108
+ * called.
109
+ *
110
+ * @param options - Constructor options.
111
+ * @param options.messenger - The messenger scoped to this controller.
112
+ * @param options.state - Initial state, merged with the defaults.
113
+ * @param options.clientType - The client writing to AUS.
114
+ */
115
+ constructor({ messenger, state, clientType, }) {
116
+ super({
117
+ messenger,
118
+ name: controllerName,
119
+ metadata: marketingConsentControllerMetadata,
120
+ state: { ...getDefaultMarketingConsentControllerState(), ...state },
121
+ });
122
+ this.#clientType = clientType;
123
+ this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
124
+ }
125
+ /**
126
+ * Reads the lock, sign-in and consent state, subscribes to their changes
127
+ * and starts the first sync. Call it once every controller this one depends
128
+ * on is registered. Calling it again does nothing.
129
+ *
130
+ * It isn't named `init` because `Wallet` from `@metamask/wallet` calls
131
+ * `init` on its instances before `AnalyticsController` is registered. Once
132
+ * `AnalyticsController` is part of `@metamask/wallet`, `init` can call this.
133
+ */
134
+ initialize() {
135
+ if (this.#initialized) {
136
+ return;
137
+ }
138
+ this.#initialized = true;
139
+ this.#isUnlocked = this.messenger.call('KeyringController:getState').isUnlocked;
140
+ this.#isSignedIn = this.messenger.call('AuthenticationController:getState').isSignedIn;
141
+ this.#lastSeenConsent = this.#getLocalConsent();
142
+ this.#subscribe();
143
+ this.#startSync();
144
+ }
145
+ /**
146
+ * Sets the user's marketing consent and saves it to AUS.
147
+ *
148
+ * Turning consent off also turns off the AUS marketing notification
149
+ * channels, before consent is saved.
150
+ *
151
+ * Before sign-in finishes (e.g. during onboarding), the change is applied
152
+ * locally and saved to AUS once the wallet is unlocked and signed in; the
153
+ * call resolves without waiting for that.
154
+ *
155
+ * A call overtaken by a newer choice (a newer call, or other code changing
156
+ * consent in AnalyticsController) resolves without waiting; the newer
157
+ * choice is saved on its own.
158
+ *
159
+ * @param enabled - Whether the user consents to marketing.
160
+ * @throws If AUS did not save the change. AUS is the source of truth, so
161
+ * the change is then dropped and local consent is re-read from AUS.
162
+ */
163
+ async setMarketingConsent(enabled) {
164
+ this.#latestConsentRequest += 1;
165
+ const request = this.#latestConsentRequest;
166
+ const applied = this.#applyLocalConsent(enabled);
167
+ // Checked after applying: the change applies locally either way, and a
168
+ // first decision is what makes syncing possible. Before sign-in finishes,
169
+ // the change stays pending until the wallet is unlocked and signed in.
170
+ if (!this.#isReady()) {
171
+ await applied;
172
+ return;
173
+ }
174
+ try {
175
+ // Wait for the sync run started above alongside AnalyticsController's
176
+ // follow-up work (e.g. resolving geolocation), not after it: if that
177
+ // work outlasts the write, waiting afterwards starts an extra AUS read.
178
+ await Promise.all([applied, this.#waitForSync(enabled)]);
179
+ }
180
+ catch (error) {
181
+ // Overtaken by a newer choice, from a newer call or from other code
182
+ // changing AnalyticsController; that choice is saved on its own.
183
+ if (request !== this.#latestConsentRequest ||
184
+ this.#getLocalConsent().optedIn !== enabled) {
185
+ return;
186
+ }
187
+ await this.#revertToAus();
188
+ throw error;
189
+ }
190
+ }
191
+ /**
192
+ * Drops a consent change AUS did not save and re-applies the AUS value
193
+ * locally, without writing anything to AUS.
194
+ *
195
+ */
196
+ async #revertToAus() {
197
+ // Locked or signed out mid-save: like a change made before sign-in, it
198
+ // stays pending and is saved after the next unlock and sign-in.
199
+ if (!this.#isReady()) {
200
+ return;
201
+ }
202
+ // Any pending change is this call's: a newer choice returns before the
203
+ // revert (see setMarketingConsent).
204
+ this.#setPendingConsent(null);
205
+ this.#session.refreshRequested = true;
206
+ try {
207
+ await this.#settleSync();
208
+ }
209
+ catch (error) {
210
+ // AUS is unreachable; the next unlock, refresh or sign-in re-reads it.
211
+ console.error('Failed to re-read marketing consent from AUS:', error);
212
+ }
213
+ }
214
+ /**
215
+ * Applies a consent choice locally and queues it to be written to AUS.
216
+ *
217
+ * @param enabled - Whether the user consents to marketing.
218
+ */
219
+ async #applyLocalConsent(enabled) {
220
+ // AnalyticsController updates consent before its first await. Queue the
221
+ // change before awaiting its follow-up work, so an older call resuming
222
+ // later cannot override a newer one.
223
+ const applied = enabled
224
+ ? this.messenger.call('AnalyticsController:optInToMarketing')
225
+ : this.messenger.call('AnalyticsController:optOutOfMarketing');
226
+ // An explicit choice is written to AUS even when it matches local consent,
227
+ // so it wins over a different value AUS may hold.
228
+ this.#setPendingConsent(enabled);
229
+ this.#startSync();
230
+ await applied;
231
+ }
232
+ /**
233
+ * Confirms the requested consent was saved to AUS.
234
+ *
235
+ * @param expectedConsent - The consent value the caller asked to save.
236
+ */
237
+ async #waitForSync(expectedConsent) {
238
+ const expectedSession = this.#session;
239
+ await this.#settleSync();
240
+ if (expectedSession !== this.#session ||
241
+ this.state.pendingMarketingConsent !== null ||
242
+ this.#session.lastSynced !== expectedConsent ||
243
+ this.#getLocalConsent().optedIn !== expectedConsent) {
244
+ throw new Error('Marketing consent was not saved to AUS');
245
+ }
246
+ }
247
+ /**
248
+ * Re-reads consent from AUS, e.g. when the wallet UI opens or the app
249
+ * returns to the foreground.
250
+ */
251
+ refresh() {
252
+ this.#session.refreshRequested = true;
253
+ this.#startSync();
254
+ }
255
+ /**
256
+ * Subscribes to the lock, sign-in and consent changes that drive syncing.
257
+ */
258
+ #subscribe() {
259
+ this.messenger.subscribe('KeyringController:unlock', () => {
260
+ this.#isUnlocked = true;
261
+ // AUS may have changed on another device while locked.
262
+ this.refresh();
263
+ });
264
+ this.messenger.subscribe('KeyringController:lock', () => {
265
+ this.#isUnlocked = false;
266
+ });
267
+ this.messenger.subscribe('AuthenticationController:stateChanged', (state) => {
268
+ const changed = this.#isSignedIn !== state.isSignedIn;
269
+ this.#isSignedIn = state.isSignedIn;
270
+ if (changed) {
271
+ this.#session = {};
272
+ this.#startSync();
273
+ }
274
+ });
275
+ this.messenger.subscribe('AnalyticsController:stateChanged', (state) => {
276
+ const prior = this.#lastSeenConsent;
277
+ const now = toLocalConsent(state);
278
+ this.#lastSeenConsent = now;
279
+ const localConsentChanged = prior.optedIn !== now.optedIn &&
280
+ prior.decided &&
281
+ now.decided &&
282
+ this.#applyingRemoteValue !== now.optedIn;
283
+ const decisionJustMade = !prior.decided && now.decided;
284
+ if (!localConsentChanged && !decisionJustMade) {
285
+ return;
286
+ }
287
+ this.#setPendingConsent(now.optedIn);
288
+ this.#startSync();
289
+ });
290
+ }
291
+ /**
292
+ * Reads local consent from AnalyticsController.
293
+ *
294
+ * @returns Whether the user opted in to marketing and whether they decided.
295
+ */
296
+ #getLocalConsent() {
297
+ return toLocalConsent(this.messenger.call('AnalyticsController:getState'));
298
+ }
299
+ /**
300
+ * Whether consent can be synced: AUS needs a bearer token, which is only
301
+ * obtainable while unlocked and signed in, and only a decided consent is
302
+ * synced.
303
+ *
304
+ * @returns True when unlocked, signed in and consent is decided.
305
+ */
306
+ #isReady() {
307
+ return (this.#isUnlocked && this.#isSignedIn && this.#getLocalConsent().decided);
308
+ }
309
+ /**
310
+ * Sets the consent change waiting to be written to AUS.
311
+ *
312
+ * @param value - The consent to write, or `null` when nothing is pending.
313
+ */
314
+ #setPendingConsent(value) {
315
+ this.update((state) => {
316
+ state.pendingMarketingConsent = value;
317
+ });
318
+ }
319
+ /**
320
+ * Throws if the session changed or the controller stopped being ready, so a
321
+ * multi-step write stops before writing to a profile that signed in since.
322
+ *
323
+ * @param session - The session the write belongs to.
324
+ */
325
+ #assertCurrentSession(session) {
326
+ if (session !== this.#session || !this.#isReady()) {
327
+ throw new Error('Marketing consent sync session ended');
328
+ }
329
+ }
330
+ /**
331
+ * Turns off the AUS marketing notification channels (push and in-app), which
332
+ * rely on marketing consent. Writes nothing when they are already off.
333
+ *
334
+ * @param session - The session the write belongs to.
335
+ */
336
+ async #turnOffMarketingNotifications(session) {
337
+ await this.messenger.call('AuthenticatedUserStorageService:invalidateQueries', {
338
+ queryKey: [
339
+ 'AuthenticatedUserStorageService:getNotificationPreferences',
340
+ ],
341
+ });
342
+ const preferences = await this.messenger.call('AuthenticatedUserStorageService:getNotificationPreferences');
343
+ if (!preferences) {
344
+ return;
345
+ }
346
+ const { marketing } = preferences;
347
+ if (!marketing.pushNotificationsEnabled &&
348
+ !marketing.inAppNotificationsEnabled) {
349
+ return;
350
+ }
351
+ this.#assertCurrentSession(session);
352
+ await this.messenger.call('AuthenticatedUserStorageService:putNotificationPreferences', {
353
+ ...preferences,
354
+ marketing: {
355
+ pushNotificationsEnabled: false,
356
+ inAppNotificationsEnabled: false,
357
+ },
358
+ }, this.#clientType);
359
+ // The write only invalidates the cached preferences; re-reading them
360
+ // publishes the new value to UIs bound to the AUS cache. A failed re-read
361
+ // must not block the consent write, the UI catches up on its next read.
362
+ await this.messenger
363
+ .call('AuthenticatedUserStorageService:getNotificationPreferences')
364
+ .catch((error) => {
365
+ console.error('Failed to refresh notification preferences:', error);
366
+ });
367
+ }
368
+ /**
369
+ * Writes consent to AUS. For an opt-out, the marketing notification channels
370
+ * go off first, so AUS never has consent off with a channel on; a failure
371
+ * leaves both to retry.
372
+ *
373
+ * @param value - The consent to write.
374
+ * @param session - The session the write belongs to.
375
+ */
376
+ async #writeConsent(value, session) {
377
+ if (!value) {
378
+ await this.#turnOffMarketingNotifications(session);
379
+ }
380
+ this.#assertCurrentSession(session);
381
+ await this.messenger.call('AuthenticatedUserStorageService:putMarketingConsent', { marketingConsentEnabled: value }, this.#clientType);
382
+ }
383
+ /**
384
+ * Reads consent from AUS and applies it locally, or writes the local value
385
+ * when AUS has none. Results are dropped if the session ended or a local
386
+ * change arrived during the read.
387
+ *
388
+ * @param session - The session the read belongs to.
389
+ */
390
+ async #reconcileWithAus(session) {
391
+ // Read fresh: AUS caches this query for a minute, and another device may
392
+ // have changed consent since.
393
+ await this.messenger.call('AuthenticatedUserStorageService:invalidateQueries', { queryKey: ['AuthenticatedUserStorageService:getMarketingConsent'] });
394
+ const remote = await this.messenger.call('AuthenticatedUserStorageService:getMarketingConsent');
395
+ if (session !== this.#session || !this.#isReady()) {
396
+ return;
397
+ }
398
+ // A local change during the read takes precedence over AUS.
399
+ if (this.state.pendingMarketingConsent !== null) {
400
+ return;
401
+ }
402
+ // Read after the checks, so it reflects any change made during the read.
403
+ const localValue = this.#getLocalConsent().optedIn;
404
+ if (remote === null) {
405
+ await this.#writeConsent(localValue, session);
406
+ session.lastSynced = localValue;
407
+ return;
408
+ }
409
+ if (remote.marketingConsentEnabled !== localValue) {
410
+ this.#applyingRemoteValue = remote.marketingConsentEnabled;
411
+ try {
412
+ if (remote.marketingConsentEnabled) {
413
+ await this.messenger.call('AnalyticsController:optInToMarketing');
414
+ }
415
+ else {
416
+ this.messenger.call('AnalyticsController:optOutOfMarketing');
417
+ }
418
+ }
419
+ finally {
420
+ this.#applyingRemoteValue = undefined;
421
+ }
422
+ }
423
+ // Another client may have revoked consent without turning the marketing
424
+ // channels off; a no-op when they already are.
425
+ if (!remote.marketingConsentEnabled) {
426
+ await this.#turnOffMarketingNotifications(session);
427
+ }
428
+ session.lastSynced = remote.marketingConsentEnabled;
429
+ }
430
+ /**
431
+ * Writes the pending change to AUS, then any newer change made during the
432
+ * write. On failure the pending change stays in state.
433
+ *
434
+ * @param session - The session the write belongs to.
435
+ */
436
+ async #flushPendingConsent(session) {
437
+ const value = this.state.pendingMarketingConsent;
438
+ if (value === null || !this.#isReady()) {
439
+ return;
440
+ }
441
+ // On failure the pending change stays in state and is retried.
442
+ await this.#writeConsent(value, session);
443
+ session.lastSynced = value;
444
+ // A newer local change made during the write is flushed next.
445
+ if (this.state.pendingMarketingConsent === value) {
446
+ this.#setPendingConsent(null);
447
+ return;
448
+ }
449
+ await this.#flushPendingConsent(session);
450
+ }
451
+ /**
452
+ * One sync run: reads AUS when nothing is pending, then writes any pending
453
+ * change.
454
+ *
455
+ * @param session - The session the run belongs to.
456
+ */
457
+ async #run(session) {
458
+ // Claim any refresh requests: this run's AUS read satisfies them. A
459
+ // request made during the run sets the flag again and starts another run.
460
+ // Every run starts from a pending local change, a new session or a
461
+ // refresh, so without a pending change AUS is always read.
462
+ session.refreshRequested = false;
463
+ if (this.state.pendingMarketingConsent === null) {
464
+ await this.#reconcileWithAus(session);
465
+ }
466
+ await this.#flushPendingConsent(session);
467
+ }
468
+ /**
469
+ * Starts a sync run when ready, or returns the one in progress. When a run
470
+ * ends, another starts if the session changed, a refresh was requested, or a
471
+ * change was queued after the run's last write.
472
+ *
473
+ * @returns The sync run in progress.
474
+ */
475
+ #sync() {
476
+ if (this.#inFlight) {
477
+ return this.#inFlight;
478
+ }
479
+ if (!this.#isReady()) {
480
+ return Promise.resolve();
481
+ }
482
+ const startedFor = this.#session;
483
+ const afterRun = (succeeded) => {
484
+ this.#inFlight = undefined;
485
+ // Re-run for a new session, or for a refresh requested mid-run; a
486
+ // refresh must not read AUS before an in-flight write has landed.
487
+ // After a successful run, a pending change was made after its flush;
488
+ // after a failed one, it is the change that failed and waits for the
489
+ // next trigger instead of retrying in a loop.
490
+ const sessionChanged = this.#session !== startedFor;
491
+ const changedAfterFlush = succeeded && this.state.pendingMarketingConsent !== null;
492
+ if (this.#isReady() &&
493
+ (sessionChanged ||
494
+ this.#session.refreshRequested === true ||
495
+ changedAfterFlush)) {
496
+ this.#startSync();
497
+ }
498
+ };
499
+ this.#inFlight = this.#run(startedFor).then(() => afterRun(true), (error) => {
500
+ const handedOff = this.#session !== startedFor;
501
+ afterRun(false);
502
+ // A run whose session ended hands off to the next session's run, so
503
+ // its error says nothing about whether the change will be saved.
504
+ if (!handedOff) {
505
+ throw error;
506
+ }
507
+ });
508
+ return this.#inFlight;
509
+ }
510
+ /**
511
+ * Starts a sync run without waiting for it, logging any failure.
512
+ */
513
+ #startSync() {
514
+ this.#sync().catch((error) => {
515
+ console.error('Failed to synchronize marketing consent with AUS:', error);
516
+ });
517
+ }
518
+ /**
519
+ * Waits until no sync run is in progress, including runs started when an
520
+ * older one hands off to a new session.
521
+ */
522
+ async #settleSync() {
523
+ await this.#sync();
524
+ if (this.#inFlight) {
525
+ await this.#settleSync();
526
+ }
527
+ }
528
+ }
529
+ //# sourceMappingURL=MarketingConsentController.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MarketingConsentController.js","sourceRoot":"","sources":["../src/MarketingConsentController.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAgB3D,kBAAkB;AAElB;;;;GAIG;AACH,MAAM,cAAc,GAAG,4BAA4B,CAAC;AA0BpD;;;;;GAKG;AACH,SAAS,cAAc,CACrB,KAGC;IAED,OAAO;QAC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AC,CACF,CAAC;QAEF,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED;;OAEG;IACH,UAAU;QACR,IAAI,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;YAC3B,OAAO,CAAC,KAAK,CAAC,mDAAmD,EAAE,KAAK,CAAC,CAAC;QAC5E,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,WAAW;QACf,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;QACnB,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACnB,MAAM,IAAI,CAAC,WAAW,EAAE,CAAC;QAC3B,CAAC;IACH,CAAC;CACF","sourcesContent":["import type {\n AnalyticsControllerGetStateAction,\n AnalyticsControllerOptInToMarketingAction,\n AnalyticsControllerOptOutOfMarketingAction,\n AnalyticsControllerState,\n} from '@metamask/analytics-controller';\nimport type {\n AuthenticatedUserStorageInvalidateQueriesAction,\n AuthenticatedUserStorageServiceGetMarketingConsentAction,\n AuthenticatedUserStorageServiceGetNotificationPreferencesAction,\n AuthenticatedUserStorageServicePutMarketingConsentAction,\n AuthenticatedUserStorageServicePutNotificationPreferencesAction,\n ClientType,\n} from '@metamask/authenticated-user-storage';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangedEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\n\nimport type { MarketingConsentControllerMethodActions } from './MarketingConsentController-method-action-types.js';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link MarketingConsentController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nconst controllerName = 'MarketingConsentController';\n\n/**\n * One signed-in period. A new session starts whenever the signed-in status\n * changes, so work started for one profile is never applied to another.\n */\ntype ConsentSyncSession = {\n /** The consent value AUS last confirmed in this session. */\n lastSynced?: boolean;\n /**\n * A refresh was requested (e.g. on unlock, since AUS may have changed on\n * another device), so AUS should be read again.\n */\n refreshRequested?: boolean;\n};\n\n/**\n * The marketing consent held by AnalyticsController.\n */\ntype LocalConsent = {\n /** Whether the user opted in to marketing. */\n optedIn: boolean;\n /** Whether the user made a marketing consent decision. */\n decided: boolean;\n};\n\n/**\n * Picks the marketing consent fields from AnalyticsController state.\n *\n * @param state - The AnalyticsController state.\n * @returns The local marketing consent.\n */\nfunction toLocalConsent(\n state: Pick<\n AnalyticsControllerState,\n 'optedInToMarketing' | 'marketingConsentDecisionMade'\n >,\n): LocalConsent {\n return {\n optedIn: state.optedInToMarketing === true,\n decided: state.marketingConsentDecisionMade === true,\n };\n}\n\n// === STATE ===\n\n/** State managed by MarketingConsentController. */\nexport type MarketingConsentControllerState = {\n /**\n * A local consent change not yet written to Authenticated User Storage, or\n * `null` when there is none. Persisted so the change survives a restart and\n * is written to whichever profile signs in next.\n */\n pendingMarketingConsent: boolean | null;\n};\n\n/**\n * The metadata for each property in {@link MarketingConsentControllerState}.\n */\nconst marketingConsentControllerMetadata = {\n pendingMarketingConsent: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n} satisfies StateMetadata<MarketingConsentControllerState>;\n\n/**\n * Returns the default state for MarketingConsentController.\n *\n * @returns The default state.\n */\nexport function getDefaultMarketingConsentControllerState(): MarketingConsentControllerState {\n return { pendingMarketingConsent: null };\n}\n\n// === MESSENGER ===\n\n/**\n * The controller methods exposed as messenger actions.\n */\nconst MESSENGER_EXPOSED_METHODS = ['setMarketingConsent', 'refresh'] as const;\n\n/**\n * Retrieves the state of the {@link MarketingConsentController}.\n */\nexport type MarketingConsentControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n MarketingConsentControllerState\n>;\n\n/**\n * Actions that {@link MarketingConsentControllerMessenger} exposes to other\n * consumers.\n */\nexport type MarketingConsentControllerActions =\n | MarketingConsentControllerGetStateAction\n | MarketingConsentControllerMethodActions;\n\n/**\n * Published when the state of {@link MarketingConsentController} changes.\n */\nexport type MarketingConsentControllerStateChangedEvent =\n ControllerStateChangedEvent<\n typeof controllerName,\n MarketingConsentControllerState\n >;\n\n/**\n * Events that {@link MarketingConsentControllerMessenger} exposes to other\n * consumers.\n */\nexport type MarketingConsentControllerEvents =\n MarketingConsentControllerStateChangedEvent;\n\ntype AuthenticationControllerState =\n AuthenticationController.AuthenticationControllerState;\n\n/**\n * Actions from other messengers that {@link MarketingConsentControllerMessenger}\n * calls.\n */\ntype AllowedActions =\n | AuthenticatedUserStorageInvalidateQueriesAction\n | AuthenticatedUserStorageServiceGetMarketingConsentAction\n | AuthenticatedUserStorageServicePutMarketingConsentAction\n | AuthenticatedUserStorageServiceGetNotificationPreferencesAction\n | AuthenticatedUserStorageServicePutNotificationPreferencesAction\n | AnalyticsControllerGetStateAction\n | AnalyticsControllerOptInToMarketingAction\n | AnalyticsControllerOptOutOfMarketingAction\n | AuthenticationController.AuthenticationControllerGetStateAction\n | KeyringControllerGetStateAction;\n\n/**\n * Events from other messengers that {@link MarketingConsentControllerMessenger}\n * subscribes to.\n */\ntype AllowedEvents =\n | ControllerStateChangedEvent<'AnalyticsController', AnalyticsControllerState>\n | ControllerStateChangedEvent<\n 'AuthenticationController',\n AuthenticationControllerState\n >\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link MarketingConsentController}.\n */\nexport type MarketingConsentControllerMessenger = Messenger<\n typeof controllerName,\n MarketingConsentControllerActions | AllowedActions,\n MarketingConsentControllerEvents | AllowedEvents\n>;\n\n// === CONTROLLER DEFINITION ===\n\n/**\n * Keeps the user's marketing consent (held locally by `AnalyticsController`)\n * in sync with their Authenticated User Storage (AUS) profile. AUS is the\n * source of truth.\n *\n * - Clients change consent with\n * {@link MarketingConsentController.setMarketingConsent}, which resolves once\n * AUS has saved the change.\n * - On sign-in, unlock or {@link MarketingConsentController.refresh}, consent\n * is read from AUS and applied locally.\n * - A local change not yet saved (e.g. made during onboarding, before sign-in\n * finishes) wins at the next sync and is written to AUS. If AUS has no record, the local value is\n * written to it.\n * - Whenever consent is off, the AUS \"marketing\" notification channels are\n * turned off too, including when another client revoked consent.\n */\nexport class MarketingConsentController extends BaseController<\n typeof controllerName,\n MarketingConsentControllerState,\n MarketingConsentControllerMessenger\n> {\n /**\n * The client sent with every AUS write.\n */\n readonly #clientType: ClientType;\n\n /**\n * Whether {@link MarketingConsentController.initialize} has run.\n */\n #initialized = false;\n\n /**\n * Whether the wallet is unlocked, kept in step with the KeyringController\n * lock and unlock events. Starts `false`, so nothing syncs before `initialize`.\n */\n #isUnlocked = false;\n\n /**\n * The last signed-in status seen, so a sign-in or sign-out can be told apart\n * from other AuthenticationController changes.\n */\n #isSignedIn = false;\n\n /**\n * The last local consent seen, so the AnalyticsController listener can tell\n * a first decision from a changed one. Read local consent with\n * {@link MarketingConsentController.#getLocalConsent} instead.\n */\n #lastSeenConsent: LocalConsent = { optedIn: false, decided: false };\n\n /**\n * The current signed-in session.\n */\n #session: ConsentSyncSession = {};\n\n /**\n * The AUS value being applied locally, so its state change is not taken for\n * a local change.\n */\n #applyingRemoteValue: boolean | undefined;\n\n /**\n * The sync run in progress, if any. Only one runs at a time.\n */\n #inFlight: Promise<void> | undefined;\n\n /**\n * Counts {@link MarketingConsentController.setMarketingConsent} calls, so a\n * call overtaken by a newer one can tell.\n */\n #latestConsentRequest = 0;\n\n /**\n * Creates a new MarketingConsentController. It doesn't read other\n * controllers or sync until {@link MarketingConsentController.initialize} is\n * called.\n *\n * @param options - Constructor options.\n * @param options.messenger - The messenger scoped to this controller.\n * @param options.state - Initial state, merged with the defaults.\n * @param options.clientType - The client writing to AUS.\n */\n constructor({\n messenger,\n state,\n clientType,\n }: {\n messenger: MarketingConsentControllerMessenger;\n state?: Partial<MarketingConsentControllerState>;\n clientType: ClientType;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: marketingConsentControllerMetadata,\n state: { ...getDefaultMarketingConsentControllerState(), ...state },\n });\n\n this.#clientType = clientType;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Reads the lock, sign-in and consent state, subscribes to their changes\n * and starts the first sync. Call it once every controller this one depends\n * on is registered. Calling it again does nothing.\n *\n * It isn't named `init` because `Wallet` from `@metamask/wallet` calls\n * `init` on its instances before `AnalyticsController` is registered. Once\n * `AnalyticsController` is part of `@metamask/wallet`, `init` can call this.\n */\n initialize(): void {\n if (this.#initialized) {\n return;\n }\n this.#initialized = true;\n\n this.#isUnlocked = this.messenger.call(\n 'KeyringController:getState',\n ).isUnlocked;\n this.#isSignedIn = this.messenger.call(\n 'AuthenticationController:getState',\n ).isSignedIn;\n this.#lastSeenConsent = this.#getLocalConsent();\n\n this.#subscribe();\n this.#startSync();\n }\n\n /**\n * Sets the user's marketing consent and saves it to AUS.\n *\n * Turning consent off also turns off the AUS marketing notification\n * channels, before consent is saved.\n *\n * Before sign-in finishes (e.g. during onboarding), the change is applied\n * locally and saved to AUS once the wallet is unlocked and signed in; the\n * call resolves without waiting for that.\n *\n * A call overtaken by a newer choice (a newer call, or other code changing\n * consent in AnalyticsController) resolves without waiting; the newer\n * choice is saved on its own.\n *\n * @param enabled - Whether the user consents to marketing.\n * @throws If AUS did not save the change. AUS is the source of truth, so\n * the change is then dropped and local consent is re-read from AUS.\n */\n async setMarketingConsent(enabled: boolean): Promise<void> {\n this.#latestConsentRequest += 1;\n const request = this.#latestConsentRequest;\n\n const applied = this.#applyLocalConsent(enabled);\n\n // Checked after applying: the change applies locally either way, and a\n // first decision is what makes syncing possible. Before sign-in finishes,\n // the change stays pending until the wallet is unlocked and signed in.\n if (!this.#isReady()) {\n await applied;\n return;\n }\n\n try {\n // Wait for the sync run started above alongside AnalyticsController's\n // follow-up work (e.g. resolving geolocation), not after it: if that\n // work outlasts the write, waiting afterwards starts an extra AUS read.\n await Promise.all([applied, this.#waitForSync(enabled)]);\n } catch (error) {\n // Overtaken by a newer choice, from a newer call or from other code\n // changing AnalyticsController; that choice is saved on its own.\n if (\n request !== this.#latestConsentRequest ||\n this.#getLocalConsent().optedIn !== enabled\n ) {\n return;\n }\n await this.#revertToAus();\n throw error;\n }\n }\n\n /**\n * Drops a consent change AUS did not save and re-applies the AUS value\n * locally, without writing anything to AUS.\n *\n */\n async #revertToAus(): Promise<void> {\n // Locked or signed out mid-save: like a change made before sign-in, it\n // stays pending and is saved after the next unlock and sign-in.\n if (!this.#isReady()) {\n return;\n }\n // Any pending change is this call's: a newer choice returns before the\n // revert (see setMarketingConsent).\n this.#setPendingConsent(null);\n this.#session.refreshRequested = true;\n try {\n await this.#settleSync();\n } catch (error) {\n // AUS is unreachable; the next unlock, refresh or sign-in re-reads it.\n console.error('Failed to re-read marketing consent from AUS:', error);\n }\n }\n\n /**\n * Applies a consent choice locally and queues it to be written to AUS.\n *\n * @param enabled - Whether the user consents to marketing.\n */\n async #applyLocalConsent(enabled: boolean): Promise<void> {\n // AnalyticsController updates consent before its first await. Queue the\n // change before awaiting its follow-up work, so an older call resuming\n // later cannot override a newer one.\n const applied = enabled\n ? this.messenger.call('AnalyticsController:optInToMarketing')\n : this.messenger.call('AnalyticsController:optOutOfMarketing');\n // An explicit choice is written to AUS even when it matches local consent,\n // so it wins over a different value AUS may hold.\n this.#setPendingConsent(enabled);\n this.#startSync();\n await applied;\n }\n\n /**\n * Confirms the requested consent was saved to AUS.\n *\n * @param expectedConsent - The consent value the caller asked to save.\n */\n async #waitForSync(expectedConsent: boolean): Promise<void> {\n const expectedSession = this.#session;\n await this.#settleSync();\n\n if (\n expectedSession !== this.#session ||\n this.state.pendingMarketingConsent !== null ||\n this.#session.lastSynced !== expectedConsent ||\n this.#getLocalConsent().optedIn !== expectedConsent\n ) {\n throw new Error('Marketing consent was not saved to AUS');\n }\n }\n\n /**\n * Re-reads consent from AUS, e.g. when the wallet UI opens or the app\n * returns to the foreground.\n */\n refresh(): void {\n this.#session.refreshRequested = true;\n this.#startSync();\n }\n\n /**\n * Subscribes to the lock, sign-in and consent changes that drive syncing.\n */\n #subscribe(): void {\n this.messenger.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n // AUS may have changed on another device while locked.\n this.refresh();\n });\n\n this.messenger.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n\n this.messenger.subscribe(\n 'AuthenticationController:stateChanged',\n (state) => {\n const changed = this.#isSignedIn !== state.isSignedIn;\n this.#isSignedIn = state.isSignedIn;\n\n if (changed) {\n this.#session = {};\n this.#startSync();\n }\n },\n );\n\n this.messenger.subscribe('AnalyticsController:stateChanged', (state) => {\n const prior = this.#lastSeenConsent;\n const now = toLocalConsent(state);\n this.#lastSeenConsent = now;\n\n const localConsentChanged =\n prior.optedIn !== now.optedIn &&\n prior.decided &&\n now.decided &&\n this.#applyingRemoteValue !== now.optedIn;\n const decisionJustMade = !prior.decided && now.decided;\n\n if (!localConsentChanged && !decisionJustMade) {\n return;\n }\n\n this.#setPendingConsent(now.optedIn);\n this.#startSync();\n });\n }\n\n /**\n * Reads local consent from AnalyticsController.\n *\n * @returns Whether the user opted in to marketing and whether they decided.\n */\n #getLocalConsent(): LocalConsent {\n return toLocalConsent(this.messenger.call('AnalyticsController:getState'));\n }\n\n /**\n * Whether consent can be synced: AUS needs a bearer token, which is only\n * obtainable while unlocked and signed in, and only a decided consent is\n * synced.\n *\n * @returns True when unlocked, signed in and consent is decided.\n */\n #isReady(): boolean {\n return (\n this.#isUnlocked && this.#isSignedIn && this.#getLocalConsent().decided\n );\n }\n\n /**\n * Sets the consent change waiting to be written to AUS.\n *\n * @param value - The consent to write, or `null` when nothing is pending.\n */\n #setPendingConsent(value: boolean | null): void {\n this.update((state) => {\n state.pendingMarketingConsent = value;\n });\n }\n\n /**\n * Throws if the session changed or the controller stopped being ready, so a\n * multi-step write stops before writing to a profile that signed in since.\n *\n * @param session - The session the write belongs to.\n */\n #assertCurrentSession(session: ConsentSyncSession): void {\n if (session !== this.#session || !this.#isReady()) {\n throw new Error('Marketing consent sync session ended');\n }\n }\n\n /**\n * Turns off the AUS marketing notification channels (push and in-app), which\n * rely on marketing consent. Writes nothing when they are already off.\n *\n * @param session - The session the write belongs to.\n */\n async #turnOffMarketingNotifications(\n session: ConsentSyncSession,\n ): Promise<void> {\n await this.messenger.call(\n 'AuthenticatedUserStorageService:invalidateQueries',\n {\n queryKey: [\n 'AuthenticatedUserStorageService:getNotificationPreferences',\n ],\n },\n );\n const preferences = await this.messenger.call(\n 'AuthenticatedUserStorageService:getNotificationPreferences',\n );\n if (!preferences) {\n return;\n }\n const { marketing } = preferences;\n if (\n !marketing.pushNotificationsEnabled &&\n !marketing.inAppNotificationsEnabled\n ) {\n return;\n }\n\n this.#assertCurrentSession(session);\n await this.messenger.call(\n 'AuthenticatedUserStorageService:putNotificationPreferences',\n {\n ...preferences,\n marketing: {\n pushNotificationsEnabled: false,\n inAppNotificationsEnabled: false,\n },\n },\n this.#clientType,\n );\n\n // The write only invalidates the cached preferences; re-reading them\n // publishes the new value to UIs bound to the AUS cache. A failed re-read\n // must not block the consent write, the UI catches up on its next read.\n await this.messenger\n .call('AuthenticatedUserStorageService:getNotificationPreferences')\n .catch((error: unknown) => {\n console.error('Failed to refresh notification preferences:', error);\n });\n }\n\n /**\n * Writes consent to AUS. For an opt-out, the marketing notification channels\n * go off first, so AUS never has consent off with a channel on; a failure\n * leaves both to retry.\n *\n * @param value - The consent to write.\n * @param session - The session the write belongs to.\n */\n async #writeConsent(\n value: boolean,\n session: ConsentSyncSession,\n ): Promise<void> {\n if (!value) {\n await this.#turnOffMarketingNotifications(session);\n }\n this.#assertCurrentSession(session);\n await this.messenger.call(\n 'AuthenticatedUserStorageService:putMarketingConsent',\n { marketingConsentEnabled: value },\n this.#clientType,\n );\n }\n\n /**\n * Reads consent from AUS and applies it locally, or writes the local value\n * when AUS has none. Results are dropped if the session ended or a local\n * change arrived during the read.\n *\n * @param session - The session the read belongs to.\n */\n async #reconcileWithAus(session: ConsentSyncSession): Promise<void> {\n // Read fresh: AUS caches this query for a minute, and another device may\n // have changed consent since.\n await this.messenger.call(\n 'AuthenticatedUserStorageService:invalidateQueries',\n { queryKey: ['AuthenticatedUserStorageService:getMarketingConsent'] },\n );\n\n const remote = await this.messenger.call(\n 'AuthenticatedUserStorageService:getMarketingConsent',\n );\n\n if (session !== this.#session || !this.#isReady()) {\n return;\n }\n\n // A local change during the read takes precedence over AUS.\n if (this.state.pendingMarketingConsent !== null) {\n return;\n }\n\n // Read after the checks, so it reflects any change made during the read.\n const localValue = this.#getLocalConsent().optedIn;\n\n if (remote === null) {\n await this.#writeConsent(localValue, session);\n session.lastSynced = localValue;\n return;\n }\n\n if (remote.marketingConsentEnabled !== localValue) {\n this.#applyingRemoteValue = remote.marketingConsentEnabled;\n try {\n if (remote.marketingConsentEnabled) {\n await this.messenger.call('AnalyticsController:optInToMarketing');\n } else {\n this.messenger.call('AnalyticsController:optOutOfMarketing');\n }\n } finally {\n this.#applyingRemoteValue = undefined;\n }\n }\n\n // Another client may have revoked consent without turning the marketing\n // channels off; a no-op when they already are.\n if (!remote.marketingConsentEnabled) {\n await this.#turnOffMarketingNotifications(session);\n }\n\n session.lastSynced = remote.marketingConsentEnabled;\n }\n\n /**\n * Writes the pending change to AUS, then any newer change made during the\n * write. On failure the pending change stays in state.\n *\n * @param session - The session the write belongs to.\n */\n async #flushPendingConsent(session: ConsentSyncSession): Promise<void> {\n const value = this.state.pendingMarketingConsent;\n if (value === null || !this.#isReady()) {\n return;\n }\n\n // On failure the pending change stays in state and is retried.\n await this.#writeConsent(value, session);\n\n session.lastSynced = value;\n // A newer local change made during the write is flushed next.\n if (this.state.pendingMarketingConsent === value) {\n this.#setPendingConsent(null);\n return;\n }\n\n await this.#flushPendingConsent(session);\n }\n\n /**\n * One sync run: reads AUS when nothing is pending, then writes any pending\n * change.\n *\n * @param session - The session the run belongs to.\n */\n async #run(session: ConsentSyncSession): Promise<void> {\n // Claim any refresh requests: this run's AUS read satisfies them. A\n // request made during the run sets the flag again and starts another run.\n // Every run starts from a pending local change, a new session or a\n // refresh, so without a pending change AUS is always read.\n session.refreshRequested = false;\n if (this.state.pendingMarketingConsent === null) {\n await this.#reconcileWithAus(session);\n }\n\n await this.#flushPendingConsent(session);\n }\n\n /**\n * Starts a sync run when ready, or returns the one in progress. When a run\n * ends, another starts if the session changed, a refresh was requested, or a\n * change was queued after the run's last write.\n *\n * @returns The sync run in progress.\n */\n #sync(): Promise<void> {\n if (this.#inFlight) {\n return this.#inFlight;\n }\n\n if (!this.#isReady()) {\n return Promise.resolve();\n }\n\n const startedFor = this.#session;\n\n const afterRun = (succeeded: boolean): void => {\n this.#inFlight = undefined;\n // Re-run for a new session, or for a refresh requested mid-run; a\n // refresh must not read AUS before an in-flight write has landed.\n // After a successful run, a pending change was made after its flush;\n // after a failed one, it is the change that failed and waits for the\n // next trigger instead of retrying in a loop.\n const sessionChanged = this.#session !== startedFor;\n const changedAfterFlush =\n succeeded && this.state.pendingMarketingConsent !== null;\n if (\n this.#isReady() &&\n (sessionChanged ||\n this.#session.refreshRequested === true ||\n changedAfterFlush)\n ) {\n this.#startSync();\n }\n };\n\n this.#inFlight = this.#run(startedFor).then(\n () => afterRun(true),\n (error: unknown) => {\n const handedOff = this.#session !== startedFor;\n afterRun(false);\n // A run whose session ended hands off to the next session's run, so\n // its error says nothing about whether the change will be saved.\n if (!handedOff) {\n throw error;\n }\n },\n );\n\n return this.#inFlight;\n }\n\n /**\n * Starts a sync run without waiting for it, logging any failure.\n */\n #startSync(): void {\n this.#sync().catch((error) => {\n console.error('Failed to synchronize marketing consent with AUS:', error);\n });\n }\n\n /**\n * Waits until no sync run is in progress, including runs started when an\n * older one hands off to a new session.\n */\n async #settleSync(): Promise<void> {\n await this.#sync();\n if (this.#inFlight) {\n await this.#settleSync();\n }\n }\n}\n"]}
@@ -0,0 +1,4 @@
1
+ export type { MarketingConsentControllerActions, MarketingConsentControllerEvents, MarketingConsentControllerGetStateAction, MarketingConsentControllerMessenger, MarketingConsentControllerState, MarketingConsentControllerStateChangedEvent, } from './MarketingConsentController.js';
2
+ export { MarketingConsentController, getDefaultMarketingConsentControllerState, } from './MarketingConsentController.js';
3
+ export type { MarketingConsentControllerRefreshAction, MarketingConsentControllerSetMarketingConsentAction, } from './MarketingConsentController-method-action-types.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,iCAAiC,EACjC,gCAAgC,EAChC,wCAAwC,EACxC,mCAAmC,EACnC,+BAA+B,EAC/B,2CAA2C,GAC5C,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,0BAA0B,EAC1B,yCAAyC,GAC1C,MAAM,iCAAiC,CAAC;AACzC,YAAY,EACV,uCAAuC,EACvC,mDAAmD,GACpD,MAAM,qDAAqD,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { MarketingConsentController, getDefaultMarketingConsentControllerState, } from './MarketingConsentController.js';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,0BAA0B,EAC1B,yCAAyC,GAC1C,MAAM,iCAAiC,CAAC","sourcesContent":["export type {\n MarketingConsentControllerActions,\n MarketingConsentControllerEvents,\n MarketingConsentControllerGetStateAction,\n MarketingConsentControllerMessenger,\n MarketingConsentControllerState,\n MarketingConsentControllerStateChangedEvent,\n} from './MarketingConsentController.js';\nexport {\n MarketingConsentController,\n getDefaultMarketingConsentControllerState,\n} from './MarketingConsentController.js';\nexport type {\n MarketingConsentControllerRefreshAction,\n MarketingConsentControllerSetMarketingConsentAction,\n} from './MarketingConsentController-method-action-types.js';\n"]}
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "@metamask-previews/marketing-consent-controller",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0-preview-686aaf7",
4
+ "description": "Keeps marketing consent in sync with Authenticated User Storage",
5
+ "keywords": [
6
+ "Ethereum",
7
+ "MetaMask"
8
+ ],
9
+ "homepage": "https://github.com/MetaMask/core/tree/main/packages/marketing-consent-controller#readme",
10
+ "bugs": {
11
+ "url": "https://github.com/MetaMask/core/issues"
12
+ },
13
+ "license": "(MIT OR Apache-2.0)",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/MetaMask/core.git"
17
+ },
18
+ "files": [
19
+ "dist/"
20
+ ],
21
+ "type": "module",
22
+ "sideEffects": false,
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public",
32
+ "registry": "https://registry.npmjs.org/"
33
+ },
34
+ "scripts": {
35
+ "build": "tsc --project tsconfig.build.json",
36
+ "build:all": "tsc --build tsconfig.build.json --verbose",
37
+ "build:clean": "yarn build:only-clean && yarn build",
38
+ "build:docs": "typedoc",
39
+ "build:only-clean": "rimraf './dist' './tsconfig.build.tsbuildinfo'",
40
+ "changelog:update": "../../scripts/update-changelog.sh @metamask/marketing-consent-controller",
41
+ "changelog:validate": "../../scripts/validate-changelog.sh @metamask/marketing-consent-controller",
42
+ "lint:tsconfigs": "node --import ../../scripts/resolver/register.ts --experimental-transform-types ../../scripts/lint-tsconfigs/lint-tsconfigs.ts",
43
+ "lint:tsconfigs:fix": "node --import ../../scripts/resolver/register.ts --experimental-transform-types ../../scripts/lint-tsconfigs/lint-tsconfigs.ts --fix",
44
+ "messenger-action-types:check": "node --import ../../scripts/resolver/register.ts --experimental-transform-types ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --esm --check",
45
+ "messenger-action-types:generate": "node --import ../../scripts/resolver/register.ts --experimental-transform-types ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --esm --generate",
46
+ "since-latest-release": "../../scripts/since-latest-release.sh",
47
+ "test": "vitest",
48
+ "test:clean": "vitest --clearCache",
49
+ "test:verbose": "vitest --reporter=verbose",
50
+ "test:watch": "vitest --watch"
51
+ },
52
+ "dependencies": {
53
+ "@metamask/analytics-controller": "^4.0.0",
54
+ "@metamask/authenticated-user-storage": "^4.1.0",
55
+ "@metamask/base-controller": "^10.1.0",
56
+ "@metamask/keyring-controller": "^28.2.0",
57
+ "@metamask/messenger": "^3.0.0",
58
+ "@metamask/profile-sync-controller": "^34.0.3"
59
+ },
60
+ "devDependencies": {
61
+ "@metamask/auto-changelog": "^6.2.1",
62
+ "@typescript/native": "npm:typescript@^7.0.2",
63
+ "@vitest/coverage-istanbul": "^5.0.0",
64
+ "rimraf": "^6.1.3",
65
+ "typedoc": "^0.28.20",
66
+ "typedoc-plugin-missing-exports": "^4.1.4",
67
+ "typescript": "npm:@typescript/typescript6@^6.0.2",
68
+ "vitest": "^5.0.0"
69
+ },
70
+ "engines": {
71
+ "node": "^22.14.0 || ^24"
72
+ }
6
73
  }