@metamask-previews/marketing-consent-controller 1.0.0-preview-e4c191e3a → 1.0.2-preview-a583980c5
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
CHANGED
|
@@ -7,10 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.0.2]
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- Bump `@metamask/profile-sync-controller` from `^34.1.0` to `^35.0.0` ([#10925](https://github.com/MetaMask/core/pull/10925))
|
|
15
|
+
|
|
16
|
+
## [1.0.1]
|
|
17
|
+
|
|
10
18
|
### Changed
|
|
11
19
|
|
|
12
20
|
- Bump `@metamask/profile-sync-controller` from `^34.0.3` to `^34.1.0` ([#10905](https://github.com/MetaMask/core/pull/10905))
|
|
13
21
|
|
|
22
|
+
### Fixed
|
|
23
|
+
|
|
24
|
+
- A client without a local marketing consent decision now reads Authenticated User Storage once unlocked and signed in, and adopts the saved decision without writing it back; with no saved decision it stays undecided ([#10920](https://github.com/MetaMask/core/pull/10920))
|
|
25
|
+
- Previously such a client never read AUS, so its first local decision (e.g. dismissing a consent prompt after a social-login restore on a new device) overwrote the decision saved in AUS.
|
|
26
|
+
|
|
14
27
|
## [1.0.0]
|
|
15
28
|
|
|
16
29
|
### Added
|
|
@@ -20,5 +33,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
20
33
|
- Add `initialize` method, which reads the controllers it depends on and starts syncing; call it once they are registered
|
|
21
34
|
- 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
|
|
22
35
|
|
|
23
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/marketing-consent-controller@1.0.
|
|
36
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/marketing-consent-controller@1.0.2...HEAD
|
|
37
|
+
[1.0.2]: https://github.com/MetaMask/core/compare/@metamask/marketing-consent-controller@1.0.1...@metamask/marketing-consent-controller@1.0.2
|
|
38
|
+
[1.0.1]: https://github.com/MetaMask/core/compare/@metamask/marketing-consent-controller@1.0.0...@metamask/marketing-consent-controller@1.0.1
|
|
24
39
|
[1.0.0]: https://github.com/MetaMask/core/releases/tag/@metamask/marketing-consent-controller@1.0.0
|
|
@@ -70,7 +70,9 @@ export type MarketingConsentControllerMessenger = Messenger<typeof controllerNam
|
|
|
70
70
|
* {@link MarketingConsentController.setMarketingConsent}, which resolves once
|
|
71
71
|
* AUS has saved the change.
|
|
72
72
|
* - On sign-in, unlock or {@link MarketingConsentController.refresh}, consent
|
|
73
|
-
* is read from AUS and applied locally.
|
|
73
|
+
* is read from AUS and applied locally. A client with no local decision (e.g. a
|
|
74
|
+
* social-login restore on a new device) adopts the decision saved in AUS, or
|
|
75
|
+
* stays undecided when there is none.
|
|
74
76
|
* - A local change not yet saved (e.g. made during onboarding, before sign-in
|
|
75
77
|
* finishes) wins at the next sync and is written to AUS. If AUS has no record, the local value is
|
|
76
78
|
* written to it.
|
|
@@ -1 +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,M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6B,CAC9B,GACD,0BAA0B,GAC1B,4BAA4B,CAAC;AAEjC;;;GAGG;AACH,MAAM,MAAM,mCAAmC,GAAG,SAAS,CACzD,OAAO,cAAc,EACrB,iCAAiC,GAAG,cAAc,EAClD,gCAAgC,GAAG,aAAa,CACjD,CAAC;AAIF
|
|
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,wCAAwC,GAAG,wBAAwB,CAC7E,OAAO,cAAc,EACrB,+BAA+B,CAChC,CAAC;A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O,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CA+BzD;IA+DD;;;OAGG;IACH,OAAO,IAAI,IAAI,CAGd;CA2WF"}
|
|
@@ -52,7 +52,9 @@ const MESSENGER_EXPOSED_METHODS = ['setMarketingConsent', 'refresh'];
|
|
|
52
52
|
* {@link MarketingConsentController.setMarketingConsent}, which resolves once
|
|
53
53
|
* AUS has saved the change.
|
|
54
54
|
* - On sign-in, unlock or {@link MarketingConsentController.refresh}, consent
|
|
55
|
-
* is read from AUS and applied locally.
|
|
55
|
+
* is read from AUS and applied locally. A client with no local decision (e.g. a
|
|
56
|
+
* social-login restore on a new device) adopts the decision saved in AUS, or
|
|
57
|
+
* stays undecided when there is none.
|
|
56
58
|
* - A local change not yet saved (e.g. made during onboarding, before sign-in
|
|
57
59
|
* finishes) wins at the next sync and is written to AUS. If AUS has no record, the local value is
|
|
58
60
|
* written to it.
|
|
@@ -280,7 +282,9 @@ export class MarketingConsentController extends BaseController {
|
|
|
280
282
|
prior.decided &&
|
|
281
283
|
now.decided &&
|
|
282
284
|
this.#applyingRemoteValue !== now.optedIn;
|
|
283
|
-
const decisionJustMade = !prior.decided &&
|
|
285
|
+
const decisionJustMade = !prior.decided &&
|
|
286
|
+
now.decided &&
|
|
287
|
+
this.#applyingRemoteValue !== now.optedIn;
|
|
284
288
|
if (!localConsentChanged && !decisionJustMade) {
|
|
285
289
|
return;
|
|
286
290
|
}
|
|
@@ -297,14 +301,22 @@ export class MarketingConsentController extends BaseController {
|
|
|
297
301
|
return toLocalConsent(this.messenger.call('AnalyticsController:getState'));
|
|
298
302
|
}
|
|
299
303
|
/**
|
|
300
|
-
* Whether
|
|
301
|
-
*
|
|
302
|
-
*
|
|
304
|
+
* Whether AUS can be read: it needs a bearer token, which is only obtainable
|
|
305
|
+
* while unlocked and signed in.
|
|
306
|
+
*
|
|
307
|
+
* @returns True when unlocked and signed in.
|
|
308
|
+
*/
|
|
309
|
+
#canReachAus() {
|
|
310
|
+
return this.#isUnlocked && this.#isSignedIn;
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Whether consent can be written to AUS: AUS must be reachable, and only a
|
|
314
|
+
* decided consent is written.
|
|
303
315
|
*
|
|
304
316
|
* @returns True when unlocked, signed in and consent is decided.
|
|
305
317
|
*/
|
|
306
318
|
#isReady() {
|
|
307
|
-
return
|
|
319
|
+
return this.#canReachAus() && this.#getLocalConsent().decided;
|
|
308
320
|
}
|
|
309
321
|
/**
|
|
310
322
|
* Sets the consent change waiting to be written to AUS.
|
|
@@ -392,7 +404,7 @@ export class MarketingConsentController extends BaseController {
|
|
|
392
404
|
// have changed consent since.
|
|
393
405
|
await this.messenger.call('AuthenticatedUserStorageService:invalidateQueries', { queryKey: ['AuthenticatedUserStorageService:getMarketingConsent'] });
|
|
394
406
|
const remote = await this.messenger.call('AuthenticatedUserStorageService:getMarketingConsent');
|
|
395
|
-
if (session !== this.#session || !this.#
|
|
407
|
+
if (session !== this.#session || !this.#canReachAus()) {
|
|
396
408
|
return;
|
|
397
409
|
}
|
|
398
410
|
// A local change during the read takes precedence over AUS.
|
|
@@ -400,13 +412,18 @@ export class MarketingConsentController extends BaseController {
|
|
|
400
412
|
return;
|
|
401
413
|
}
|
|
402
414
|
// Read after the checks, so it reflects any change made during the read.
|
|
403
|
-
const localValue = this.#getLocalConsent()
|
|
415
|
+
const { optedIn: localValue, decided } = this.#getLocalConsent();
|
|
404
416
|
if (remote === null) {
|
|
405
|
-
|
|
406
|
-
|
|
417
|
+
// Without a local decision there is nothing to write; the user is asked,
|
|
418
|
+
// and that decision is written as a local change.
|
|
419
|
+
if (decided) {
|
|
420
|
+
await this.#writeConsent(localValue, session);
|
|
421
|
+
session.lastSynced = localValue;
|
|
422
|
+
}
|
|
407
423
|
return;
|
|
408
424
|
}
|
|
409
|
-
|
|
425
|
+
// An undecided client adopts the decision saved in AUS.
|
|
426
|
+
if (!decided || remote.marketingConsentEnabled !== localValue) {
|
|
410
427
|
this.#applyingRemoteValue = remote.marketingConsentEnabled;
|
|
411
428
|
try {
|
|
412
429
|
if (remote.marketingConsentEnabled) {
|
|
@@ -476,7 +493,7 @@ export class MarketingConsentController extends BaseController {
|
|
|
476
493
|
if (this.#inFlight) {
|
|
477
494
|
return this.#inFlight;
|
|
478
495
|
}
|
|
479
|
-
if (!this.#
|
|
496
|
+
if (!this.#canReachAus()) {
|
|
480
497
|
return Promise.resolve();
|
|
481
498
|
}
|
|
482
499
|
const startedFor = this.#session;
|
|
@@ -489,7 +506,7 @@ export class MarketingConsentController extends BaseController {
|
|
|
489
506
|
// next trigger instead of retrying in a loop.
|
|
490
507
|
const sessionChanged = this.#session !== startedFor;
|
|
491
508
|
const changedAfterFlush = succeeded && this.state.pendingMarketingConsent !== null;
|
|
492
|
-
if (this.#
|
|
509
|
+
if (this.#canReachAus() &&
|
|
493
510
|
(sessionChanged ||
|
|
494
511
|
this.#session.refreshRequested === true ||
|
|
495
512
|
changedAfterFlush)) {
|
|
@@ -1 +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;QACL,OAAO,EAAE,KAAK,CAAC,kBAAkB,KAAK,IAAI;QAC1C,OAAO,EAAE,KAAK,CAAC,4BAA4B,KAAK,IAAI;KACrD,CAAC;AACJ,CAAC;AAcD;;GAEG;AACH,MAAM,kCAAkC,GAAG;IACzC,uBAAuB,EAAE;QACvB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,KAAK;KAChB;CACuD,CAAC;AAE3D;;;;GAIG;AACH,MAAM,UAAU,yCAAyC;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,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"]}
|
|
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;QACL,OAAO,EAAE,KAAK,CAAC,kBAAkB,KAAK,IAAI;QAC1C,OAAO,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,GAAG,IAAI,CAAC,QAAQ,KAAK,UAAU,CAAC;YAC/C,QAAQ,CAAC,KAAK,CAAC,CAAC;YAChB,oEAAoE;YACpE,iEAAiE;YACjE,IAAI,CAAC,SAAS,EAAE,CAAC;gBACf,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC,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. A client with no local decision (e.g. a\n * social-login restore on a new device) adopts the decision saved in AUS, or\n * stays undecided when there is none.\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 =\n !prior.decided &&\n now.decided &&\n this.#applyingRemoteValue !== now.optedIn;\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 AUS can be read: it needs a bearer token, which is only obtainable\n * while unlocked and signed in.\n *\n * @returns True when unlocked and signed in.\n */\n #canReachAus(): boolean {\n return this.#isUnlocked && this.#isSignedIn;\n }\n\n /**\n * Whether consent can be written to AUS: AUS must be reachable, and only a\n * decided consent is written.\n *\n * @returns True when unlocked, signed in and consent is decided.\n */\n #isReady(): boolean {\n return this.#canReachAus() && this.#getLocalConsent().decided;\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.#canReachAus()) {\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 { optedIn: localValue, decided } = this.#getLocalConsent();\n\n if (remote === null) {\n // Without a local decision there is nothing to write; the user is asked,\n // and that decision is written as a local change.\n if (decided) {\n await this.#writeConsent(localValue, session);\n session.lastSynced = localValue;\n }\n return;\n }\n\n // An undecided client adopts the decision saved in AUS.\n if (!decided || 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.#canReachAus()) {\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.#canReachAus() &&\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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/marketing-consent-controller",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.2-preview-a583980c5",
|
|
4
4
|
"description": "Keeps marketing consent in sync with Authenticated User Storage",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"@metamask/base-controller": "^10.1.0",
|
|
56
56
|
"@metamask/keyring-controller": "^28.2.0",
|
|
57
57
|
"@metamask/messenger": "^3.0.0",
|
|
58
|
-
"@metamask/profile-sync-controller": "^
|
|
58
|
+
"@metamask/profile-sync-controller": "^35.0.0"
|
|
59
59
|
},
|
|
60
60
|
"devDependencies": {
|
|
61
61
|
"@metamask/auto-changelog": "^6.2.1",
|