@metamask-previews/marketing-consent-controller 0.0.0-preview-7ef511c85 → 0.0.0-preview-5e24e4d22
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 +0 -7
- package/LICENSE.APACHE2 +1 -1
- package/README.md +0 -54
- package/dist/index.d.ts +7 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -11
- package/dist/MarketingConsentController-method-action-types.d.ts +0 -40
- package/dist/MarketingConsentController-method-action-types.d.ts.map +0 -1
- package/dist/MarketingConsentController-method-action-types.js +0 -6
- package/dist/MarketingConsentController-method-action-types.js.map +0 -1
- package/dist/MarketingConsentController.d.ts +0 -133
- package/dist/MarketingConsentController.d.ts.map +0 -1
- package/dist/MarketingConsentController.js +0 -525
- package/dist/MarketingConsentController.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,11 +7,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
-
### Added
|
|
11
|
-
|
|
12
|
-
- Initial release ([#10821](https://github.com/MetaMask/core/pull/10821))
|
|
13
|
-
- Add `MarketingConsentController`, which keeps marketing consent in sync with Authenticated User Storage and turns off marketing notification channels before an opt-out is saved
|
|
14
|
-
- Add `initialize` method, which reads the controllers it depends on and starts syncing; call it once they are registered
|
|
15
|
-
- 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
|
|
16
|
-
|
|
17
10
|
[Unreleased]: https://github.com/MetaMask/core/
|
package/LICENSE.APACHE2
CHANGED
|
@@ -186,7 +186,7 @@
|
|
|
186
186
|
same "printed page" as the copyright notice for easier
|
|
187
187
|
identification within third-party archives.
|
|
188
188
|
|
|
189
|
-
Copyright
|
|
189
|
+
Copyright 2026 MetaMask
|
|
190
190
|
|
|
191
191
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
192
|
you may not use this file except in compliance with the License.
|
package/README.md
CHANGED
|
@@ -10,60 +10,6 @@ or
|
|
|
10
10
|
|
|
11
11
|
`npm install @metamask/marketing-consent-controller`
|
|
12
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
13
|
## Contributing
|
|
68
14
|
|
|
69
15
|
This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme).
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Example function that returns a greeting for the given name.
|
|
3
|
+
*
|
|
4
|
+
* @param name - The name to greet.
|
|
5
|
+
* @returns The greeting.
|
|
6
|
+
*/
|
|
7
|
+
export default function greeter(name: string): string;
|
|
4
8
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAC,OAAO,UAAU,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEpD"}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,10 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Example function that returns a greeting for the given name.
|
|
3
|
+
*
|
|
4
|
+
* @param name - The name to greet.
|
|
5
|
+
* @returns The greeting.
|
|
6
|
+
*/
|
|
7
|
+
export default function greeter(name) {
|
|
8
|
+
return `Hello, ${name}!`;
|
|
9
|
+
}
|
|
2
10
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAC,OAAO,UAAU,OAAO,CAAC,IAAY;IAC1C,OAAO,UAAU,IAAI,GAAG,CAAC;AAC3B,CAAC","sourcesContent":["/**\n * Example function that returns a greeting for the given name.\n *\n * @param name - The name to greet.\n * @returns The greeting.\n */\nexport default function greeter(name: string): string {\n return `Hello, ${name}!`;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/marketing-consent-controller",
|
|
3
|
-
"version": "0.0.0-preview-
|
|
3
|
+
"version": "0.0.0-preview-5e24e4d22",
|
|
4
4
|
"description": "Keeps marketing consent in sync with Authenticated User Storage",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|
|
@@ -41,22 +41,14 @@
|
|
|
41
41
|
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/marketing-consent-controller",
|
|
42
42
|
"lint:tsconfigs": "node --import ../../scripts/resolver/register.ts --experimental-transform-types ../../scripts/lint-tsconfigs/lint-tsconfigs.ts",
|
|
43
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 --
|
|
45
|
-
"messenger-action-types:generate": "node --import ../../scripts/resolver/register.ts --experimental-transform-types ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --
|
|
44
|
+
"messenger-action-types:check": "node --import ../../scripts/resolver/register.ts --experimental-transform-types ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --check",
|
|
45
|
+
"messenger-action-types:generate": "node --import ../../scripts/resolver/register.ts --experimental-transform-types ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --generate",
|
|
46
46
|
"since-latest-release": "../../scripts/since-latest-release.sh",
|
|
47
47
|
"test": "vitest",
|
|
48
48
|
"test:clean": "vitest --clearCache",
|
|
49
49
|
"test:verbose": "vitest --reporter=verbose",
|
|
50
50
|
"test:watch": "vitest --watch"
|
|
51
51
|
},
|
|
52
|
-
"dependencies": {
|
|
53
|
-
"@metamask/analytics-controller": "^4.0.0",
|
|
54
|
-
"@metamask/authenticated-user-storage": "^4.1.0",
|
|
55
|
-
"@metamask/base-controller": "^10.0.0",
|
|
56
|
-
"@metamask/keyring-controller": "^28.2.0",
|
|
57
|
-
"@metamask/messenger": "^3.0.0",
|
|
58
|
-
"@metamask/profile-sync-controller": "^34.0.3"
|
|
59
|
-
},
|
|
60
52
|
"devDependencies": {
|
|
61
53
|
"@metamask/auto-changelog": "^6.2.1",
|
|
62
54
|
"@typescript/native": "npm:typescript@^7.0.2",
|
|
@@ -1,40 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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"}
|
|
@@ -1 +0,0 @@
|
|
|
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"]}
|
|
@@ -1,133 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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,y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,CAAC;KACxB,EAcA;IAED;;;;;;;;OAQG;IACH,UAAU,IAAI,IAAI,CAgBjB;IAED;;;;;;;;;;;;;;;;;OAiBG;IACG,mBAAmB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CA2BzD;IA+DD;;;OAGG;IACH,OAAO,IAAI,IAAI,CAGd;CA4VF"}
|
|
@@ -1,525 +0,0 @@
|
|
|
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
|
-
await 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
|
-
return;
|
|
172
|
-
}
|
|
173
|
-
try {
|
|
174
|
-
await this.#waitForSync(enabled);
|
|
175
|
-
}
|
|
176
|
-
catch (error) {
|
|
177
|
-
// Overtaken by a newer choice, from a newer call or from other code
|
|
178
|
-
// changing AnalyticsController; that choice is saved on its own.
|
|
179
|
-
if (request !== this.#latestConsentRequest ||
|
|
180
|
-
this.#getLocalConsent().optedIn !== enabled) {
|
|
181
|
-
return;
|
|
182
|
-
}
|
|
183
|
-
await this.#revertToAus();
|
|
184
|
-
throw error;
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
/**
|
|
188
|
-
* Drops a consent change AUS did not save and re-applies the AUS value
|
|
189
|
-
* locally, without writing anything to AUS.
|
|
190
|
-
*
|
|
191
|
-
*/
|
|
192
|
-
async #revertToAus() {
|
|
193
|
-
// Locked or signed out mid-save: like a change made before sign-in, it
|
|
194
|
-
// stays pending and is saved after the next unlock and sign-in.
|
|
195
|
-
if (!this.#isReady()) {
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
// Any pending change is this call's: a newer choice returns before the
|
|
199
|
-
// revert (see setMarketingConsent).
|
|
200
|
-
this.#setPendingConsent(null);
|
|
201
|
-
this.#session.refreshRequested = true;
|
|
202
|
-
try {
|
|
203
|
-
await this.#settleSync();
|
|
204
|
-
}
|
|
205
|
-
catch (error) {
|
|
206
|
-
// AUS is unreachable; the next unlock, refresh or sign-in re-reads it.
|
|
207
|
-
console.error('Failed to re-read marketing consent from AUS:', error);
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
/**
|
|
211
|
-
* Applies a consent choice locally and queues it to be written to AUS.
|
|
212
|
-
*
|
|
213
|
-
* @param enabled - Whether the user consents to marketing.
|
|
214
|
-
*/
|
|
215
|
-
async #applyLocalConsent(enabled) {
|
|
216
|
-
// AnalyticsController updates consent before its first await. Queue the
|
|
217
|
-
// change before awaiting its follow-up work, so an older call resuming
|
|
218
|
-
// later cannot override a newer one.
|
|
219
|
-
const applied = enabled
|
|
220
|
-
? this.messenger.call('AnalyticsController:optInToMarketing')
|
|
221
|
-
: this.messenger.call('AnalyticsController:optOutOfMarketing');
|
|
222
|
-
// An explicit choice is written to AUS even when it matches local consent,
|
|
223
|
-
// so it wins over a different value AUS may hold.
|
|
224
|
-
this.#setPendingConsent(enabled);
|
|
225
|
-
this.#startSync();
|
|
226
|
-
await applied;
|
|
227
|
-
}
|
|
228
|
-
/**
|
|
229
|
-
* Confirms the requested consent was saved to AUS.
|
|
230
|
-
*
|
|
231
|
-
* @param expectedConsent - The consent value the caller asked to save.
|
|
232
|
-
*/
|
|
233
|
-
async #waitForSync(expectedConsent) {
|
|
234
|
-
const expectedSession = this.#session;
|
|
235
|
-
await this.#settleSync();
|
|
236
|
-
if (expectedSession !== this.#session ||
|
|
237
|
-
this.state.pendingMarketingConsent !== null ||
|
|
238
|
-
this.#session.lastSynced !== expectedConsent ||
|
|
239
|
-
this.#getLocalConsent().optedIn !== expectedConsent) {
|
|
240
|
-
throw new Error('Marketing consent was not saved to AUS');
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
/**
|
|
244
|
-
* Re-reads consent from AUS, e.g. when the wallet UI opens or the app
|
|
245
|
-
* returns to the foreground.
|
|
246
|
-
*/
|
|
247
|
-
refresh() {
|
|
248
|
-
this.#session.refreshRequested = true;
|
|
249
|
-
this.#startSync();
|
|
250
|
-
}
|
|
251
|
-
/**
|
|
252
|
-
* Subscribes to the lock, sign-in and consent changes that drive syncing.
|
|
253
|
-
*/
|
|
254
|
-
#subscribe() {
|
|
255
|
-
this.messenger.subscribe('KeyringController:unlock', () => {
|
|
256
|
-
this.#isUnlocked = true;
|
|
257
|
-
// AUS may have changed on another device while locked.
|
|
258
|
-
this.refresh();
|
|
259
|
-
});
|
|
260
|
-
this.messenger.subscribe('KeyringController:lock', () => {
|
|
261
|
-
this.#isUnlocked = false;
|
|
262
|
-
});
|
|
263
|
-
this.messenger.subscribe('AuthenticationController:stateChanged', (state) => {
|
|
264
|
-
const changed = this.#isSignedIn !== state.isSignedIn;
|
|
265
|
-
this.#isSignedIn = state.isSignedIn;
|
|
266
|
-
if (changed) {
|
|
267
|
-
this.#session = {};
|
|
268
|
-
this.#startSync();
|
|
269
|
-
}
|
|
270
|
-
});
|
|
271
|
-
this.messenger.subscribe('AnalyticsController:stateChanged', (state) => {
|
|
272
|
-
const prior = this.#lastSeenConsent;
|
|
273
|
-
const now = toLocalConsent(state);
|
|
274
|
-
this.#lastSeenConsent = now;
|
|
275
|
-
const localConsentChanged = prior.optedIn !== now.optedIn &&
|
|
276
|
-
prior.decided &&
|
|
277
|
-
now.decided &&
|
|
278
|
-
this.#applyingRemoteValue !== now.optedIn;
|
|
279
|
-
const decisionJustMade = !prior.decided && now.decided;
|
|
280
|
-
if (!localConsentChanged && !decisionJustMade) {
|
|
281
|
-
return;
|
|
282
|
-
}
|
|
283
|
-
this.#setPendingConsent(now.optedIn);
|
|
284
|
-
this.#startSync();
|
|
285
|
-
});
|
|
286
|
-
}
|
|
287
|
-
/**
|
|
288
|
-
* Reads local consent from AnalyticsController.
|
|
289
|
-
*
|
|
290
|
-
* @returns Whether the user opted in to marketing and whether they decided.
|
|
291
|
-
*/
|
|
292
|
-
#getLocalConsent() {
|
|
293
|
-
return toLocalConsent(this.messenger.call('AnalyticsController:getState'));
|
|
294
|
-
}
|
|
295
|
-
/**
|
|
296
|
-
* Whether consent can be synced: AUS needs a bearer token, which is only
|
|
297
|
-
* obtainable while unlocked and signed in, and only a decided consent is
|
|
298
|
-
* synced.
|
|
299
|
-
*
|
|
300
|
-
* @returns True when unlocked, signed in and consent is decided.
|
|
301
|
-
*/
|
|
302
|
-
#isReady() {
|
|
303
|
-
return (this.#isUnlocked && this.#isSignedIn && this.#getLocalConsent().decided);
|
|
304
|
-
}
|
|
305
|
-
/**
|
|
306
|
-
* Sets the consent change waiting to be written to AUS.
|
|
307
|
-
*
|
|
308
|
-
* @param value - The consent to write, or `null` when nothing is pending.
|
|
309
|
-
*/
|
|
310
|
-
#setPendingConsent(value) {
|
|
311
|
-
this.update((state) => {
|
|
312
|
-
state.pendingMarketingConsent = value;
|
|
313
|
-
});
|
|
314
|
-
}
|
|
315
|
-
/**
|
|
316
|
-
* Throws if the session changed or the controller stopped being ready, so a
|
|
317
|
-
* multi-step write stops before writing to a profile that signed in since.
|
|
318
|
-
*
|
|
319
|
-
* @param session - The session the write belongs to.
|
|
320
|
-
*/
|
|
321
|
-
#assertCurrentSession(session) {
|
|
322
|
-
if (session !== this.#session || !this.#isReady()) {
|
|
323
|
-
throw new Error('Marketing consent sync session ended');
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
/**
|
|
327
|
-
* Turns off the AUS marketing notification channels (push and in-app), which
|
|
328
|
-
* rely on marketing consent. Writes nothing when they are already off.
|
|
329
|
-
*
|
|
330
|
-
* @param session - The session the write belongs to.
|
|
331
|
-
*/
|
|
332
|
-
async #turnOffMarketingNotifications(session) {
|
|
333
|
-
await this.messenger.call('AuthenticatedUserStorageService:invalidateQueries', {
|
|
334
|
-
queryKey: [
|
|
335
|
-
'AuthenticatedUserStorageService:getNotificationPreferences',
|
|
336
|
-
],
|
|
337
|
-
});
|
|
338
|
-
const preferences = await this.messenger.call('AuthenticatedUserStorageService:getNotificationPreferences');
|
|
339
|
-
if (!preferences) {
|
|
340
|
-
return;
|
|
341
|
-
}
|
|
342
|
-
const { marketing } = preferences;
|
|
343
|
-
if (!marketing.pushNotificationsEnabled &&
|
|
344
|
-
!marketing.inAppNotificationsEnabled) {
|
|
345
|
-
return;
|
|
346
|
-
}
|
|
347
|
-
this.#assertCurrentSession(session);
|
|
348
|
-
await this.messenger.call('AuthenticatedUserStorageService:putNotificationPreferences', {
|
|
349
|
-
...preferences,
|
|
350
|
-
marketing: {
|
|
351
|
-
pushNotificationsEnabled: false,
|
|
352
|
-
inAppNotificationsEnabled: false,
|
|
353
|
-
},
|
|
354
|
-
}, this.#clientType);
|
|
355
|
-
// The write only invalidates the cached preferences; re-reading them
|
|
356
|
-
// publishes the new value to UIs bound to the AUS cache. A failed re-read
|
|
357
|
-
// must not block the consent write, the UI catches up on its next read.
|
|
358
|
-
await this.messenger
|
|
359
|
-
.call('AuthenticatedUserStorageService:getNotificationPreferences')
|
|
360
|
-
.catch((error) => {
|
|
361
|
-
console.error('Failed to refresh notification preferences:', error);
|
|
362
|
-
});
|
|
363
|
-
}
|
|
364
|
-
/**
|
|
365
|
-
* Writes consent to AUS. For an opt-out, the marketing notification channels
|
|
366
|
-
* go off first, so AUS never has consent off with a channel on; a failure
|
|
367
|
-
* leaves both to retry.
|
|
368
|
-
*
|
|
369
|
-
* @param value - The consent to write.
|
|
370
|
-
* @param session - The session the write belongs to.
|
|
371
|
-
*/
|
|
372
|
-
async #writeConsent(value, session) {
|
|
373
|
-
if (!value) {
|
|
374
|
-
await this.#turnOffMarketingNotifications(session);
|
|
375
|
-
}
|
|
376
|
-
this.#assertCurrentSession(session);
|
|
377
|
-
await this.messenger.call('AuthenticatedUserStorageService:putMarketingConsent', { marketingConsentEnabled: value }, this.#clientType);
|
|
378
|
-
}
|
|
379
|
-
/**
|
|
380
|
-
* Reads consent from AUS and applies it locally, or writes the local value
|
|
381
|
-
* when AUS has none. Results are dropped if the session ended or a local
|
|
382
|
-
* change arrived during the read.
|
|
383
|
-
*
|
|
384
|
-
* @param session - The session the read belongs to.
|
|
385
|
-
*/
|
|
386
|
-
async #reconcileWithAus(session) {
|
|
387
|
-
// Read fresh: AUS caches this query for a minute, and another device may
|
|
388
|
-
// have changed consent since.
|
|
389
|
-
await this.messenger.call('AuthenticatedUserStorageService:invalidateQueries', { queryKey: ['AuthenticatedUserStorageService:getMarketingConsent'] });
|
|
390
|
-
const remote = await this.messenger.call('AuthenticatedUserStorageService:getMarketingConsent');
|
|
391
|
-
if (session !== this.#session || !this.#isReady()) {
|
|
392
|
-
return;
|
|
393
|
-
}
|
|
394
|
-
// A local change during the read takes precedence over AUS.
|
|
395
|
-
if (this.state.pendingMarketingConsent !== null) {
|
|
396
|
-
return;
|
|
397
|
-
}
|
|
398
|
-
// Read after the checks, so it reflects any change made during the read.
|
|
399
|
-
const localValue = this.#getLocalConsent().optedIn;
|
|
400
|
-
if (remote === null) {
|
|
401
|
-
await this.#writeConsent(localValue, session);
|
|
402
|
-
session.lastSynced = localValue;
|
|
403
|
-
return;
|
|
404
|
-
}
|
|
405
|
-
if (remote.marketingConsentEnabled !== localValue) {
|
|
406
|
-
this.#applyingRemoteValue = remote.marketingConsentEnabled;
|
|
407
|
-
try {
|
|
408
|
-
if (remote.marketingConsentEnabled) {
|
|
409
|
-
await this.messenger.call('AnalyticsController:optInToMarketing');
|
|
410
|
-
}
|
|
411
|
-
else {
|
|
412
|
-
this.messenger.call('AnalyticsController:optOutOfMarketing');
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
finally {
|
|
416
|
-
this.#applyingRemoteValue = undefined;
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
// Another client may have revoked consent without turning the marketing
|
|
420
|
-
// channels off; a no-op when they already are.
|
|
421
|
-
if (!remote.marketingConsentEnabled) {
|
|
422
|
-
await this.#turnOffMarketingNotifications(session);
|
|
423
|
-
}
|
|
424
|
-
session.lastSynced = remote.marketingConsentEnabled;
|
|
425
|
-
}
|
|
426
|
-
/**
|
|
427
|
-
* Writes the pending change to AUS, then any newer change made during the
|
|
428
|
-
* write. On failure the pending change stays in state.
|
|
429
|
-
*
|
|
430
|
-
* @param session - The session the write belongs to.
|
|
431
|
-
*/
|
|
432
|
-
async #flushPendingConsent(session) {
|
|
433
|
-
const value = this.state.pendingMarketingConsent;
|
|
434
|
-
if (value === null || !this.#isReady()) {
|
|
435
|
-
return;
|
|
436
|
-
}
|
|
437
|
-
// On failure the pending change stays in state and is retried.
|
|
438
|
-
await this.#writeConsent(value, session);
|
|
439
|
-
session.lastSynced = value;
|
|
440
|
-
// A newer local change made during the write is flushed next.
|
|
441
|
-
if (this.state.pendingMarketingConsent === value) {
|
|
442
|
-
this.#setPendingConsent(null);
|
|
443
|
-
return;
|
|
444
|
-
}
|
|
445
|
-
await this.#flushPendingConsent(session);
|
|
446
|
-
}
|
|
447
|
-
/**
|
|
448
|
-
* One sync run: reads AUS when nothing is pending, then writes any pending
|
|
449
|
-
* change.
|
|
450
|
-
*
|
|
451
|
-
* @param session - The session the run belongs to.
|
|
452
|
-
*/
|
|
453
|
-
async #run(session) {
|
|
454
|
-
// Claim any refresh requests: this run's AUS read satisfies them. A
|
|
455
|
-
// request made during the run sets the flag again and starts another run.
|
|
456
|
-
// Every run starts from a pending local change, a new session or a
|
|
457
|
-
// refresh, so without a pending change AUS is always read.
|
|
458
|
-
session.refreshRequested = false;
|
|
459
|
-
if (this.state.pendingMarketingConsent === null) {
|
|
460
|
-
await this.#reconcileWithAus(session);
|
|
461
|
-
}
|
|
462
|
-
await this.#flushPendingConsent(session);
|
|
463
|
-
}
|
|
464
|
-
/**
|
|
465
|
-
* Starts a sync run when ready, or returns the one in progress. When a run
|
|
466
|
-
* ends, another starts if the session changed, a refresh was requested, or a
|
|
467
|
-
* change was queued after the run's last write.
|
|
468
|
-
*
|
|
469
|
-
* @returns The sync run in progress.
|
|
470
|
-
*/
|
|
471
|
-
#sync() {
|
|
472
|
-
if (this.#inFlight) {
|
|
473
|
-
return this.#inFlight;
|
|
474
|
-
}
|
|
475
|
-
if (!this.#isReady()) {
|
|
476
|
-
return Promise.resolve();
|
|
477
|
-
}
|
|
478
|
-
const startedFor = this.#session;
|
|
479
|
-
const afterRun = (succeeded) => {
|
|
480
|
-
this.#inFlight = undefined;
|
|
481
|
-
// Re-run for a new session, or for a refresh requested mid-run; a
|
|
482
|
-
// refresh must not read AUS before an in-flight write has landed.
|
|
483
|
-
// After a successful run, a pending change was made after its flush;
|
|
484
|
-
// after a failed one, it is the change that failed and waits for the
|
|
485
|
-
// next trigger instead of retrying in a loop.
|
|
486
|
-
const sessionChanged = this.#session !== startedFor;
|
|
487
|
-
const changedAfterFlush = succeeded && this.state.pendingMarketingConsent !== null;
|
|
488
|
-
if (this.#isReady() &&
|
|
489
|
-
(sessionChanged ||
|
|
490
|
-
this.#session.refreshRequested === true ||
|
|
491
|
-
changedAfterFlush)) {
|
|
492
|
-
this.#startSync();
|
|
493
|
-
}
|
|
494
|
-
};
|
|
495
|
-
this.#inFlight = this.#run(startedFor).then(() => afterRun(true), (error) => {
|
|
496
|
-
const handedOff = this.#session !== startedFor;
|
|
497
|
-
afterRun(false);
|
|
498
|
-
// A run whose session ended hands off to the next session's run, so
|
|
499
|
-
// its error says nothing about whether the change will be saved.
|
|
500
|
-
if (!handedOff) {
|
|
501
|
-
throw error;
|
|
502
|
-
}
|
|
503
|
-
});
|
|
504
|
-
return this.#inFlight;
|
|
505
|
-
}
|
|
506
|
-
/**
|
|
507
|
-
* Starts a sync run without waiting for it, logging any failure.
|
|
508
|
-
*/
|
|
509
|
-
#startSync() {
|
|
510
|
-
this.#sync().catch((error) => {
|
|
511
|
-
console.error('Failed to synchronize marketing consent with AUS:', error);
|
|
512
|
-
});
|
|
513
|
-
}
|
|
514
|
-
/**
|
|
515
|
-
* Waits until no sync run is in progress, including runs started when an
|
|
516
|
-
* older one hands off to a new session.
|
|
517
|
-
*/
|
|
518
|
-
async #settleSync() {
|
|
519
|
-
await this.#sync();
|
|
520
|
-
if (this.#inFlight) {
|
|
521
|
-
await this.#settleSync();
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
}
|
|
525
|
-
//# sourceMappingURL=MarketingConsentController.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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,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ACxB,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 await 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 return;\n }\n\n try {\n await 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"]}
|