@metamask-previews/profile-sync-controller 29.0.0-preview-6b4bcdab3 → 29.0.0-preview-0b5bfc2
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 +5 -2
- package/dist/controllers/authentication/AuthenticationController.cjs +39 -22
- package/dist/controllers/authentication/AuthenticationController.cjs.map +1 -1
- package/dist/controllers/authentication/AuthenticationController.d.cts +2 -3
- package/dist/controllers/authentication/AuthenticationController.d.cts.map +1 -1
- package/dist/controllers/authentication/AuthenticationController.d.mts +2 -3
- package/dist/controllers/authentication/AuthenticationController.d.mts.map +1 -1
- package/dist/controllers/authentication/AuthenticationController.mjs +39 -22
- package/dist/controllers/authentication/AuthenticationController.mjs.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.cjs +18 -14
- package/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.d.cts +2 -3
- package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.d.mts +2 -3
- package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.mjs +18 -14
- package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
- package/dist/shared/storage-schema.cjs +0 -1
- package/dist/shared/storage-schema.cjs.map +1 -1
- package/dist/shared/storage-schema.d.cts +0 -1
- package/dist/shared/storage-schema.d.cts.map +1 -1
- package/dist/shared/storage-schema.d.mts +0 -1
- package/dist/shared/storage-schema.d.mts.map +1 -1
- package/dist/shared/storage-schema.mjs +0 -1
- package/dist/shared/storage-schema.mjs.map +1 -1
- package/dist/shared/utils/hd-keyring-seed.cjs +49 -0
- package/dist/shared/utils/hd-keyring-seed.cjs.map +1 -0
- package/dist/shared/utils/hd-keyring-seed.d.cts +27 -0
- package/dist/shared/utils/hd-keyring-seed.d.cts.map +1 -0
- package/dist/shared/utils/hd-keyring-seed.d.mts +27 -0
- package/dist/shared/utils/hd-keyring-seed.d.mts.map +1 -0
- package/dist/shared/utils/hd-keyring-seed.mjs +45 -0
- package/dist/shared/utils/hd-keyring-seed.mjs.map +1 -0
- package/dist/shared/utils/message-signing.cjs +147 -0
- package/dist/shared/utils/message-signing.cjs.map +1 -0
- package/dist/shared/utils/message-signing.d.cts +73 -0
- package/dist/shared/utils/message-signing.d.cts.map +1 -0
- package/dist/shared/utils/message-signing.d.mts +73 -0
- package/dist/shared/utils/message-signing.d.mts.map +1 -0
- package/dist/shared/utils/message-signing.mjs +140 -0
- package/dist/shared/utils/message-signing.mjs.map +1 -0
- package/package.json +4 -4
- package/dist/controllers/authentication/auth-snap-requests.cjs +0 -44
- package/dist/controllers/authentication/auth-snap-requests.cjs.map +0 -1
- package/dist/controllers/authentication/auth-snap-requests.d.cts +0 -21
- package/dist/controllers/authentication/auth-snap-requests.d.cts.map +0 -1
- package/dist/controllers/authentication/auth-snap-requests.d.mts +0 -21
- package/dist/controllers/authentication/auth-snap-requests.d.mts.map +0 -1
- package/dist/controllers/authentication/auth-snap-requests.mjs +0 -39
- package/dist/controllers/authentication/auth-snap-requests.mjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,8 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
9
9
|
|
|
10
10
|
### Changed
|
|
11
11
|
|
|
12
|
-
-
|
|
13
|
-
-
|
|
12
|
+
- **BREAKING:** Derive auth and user-storage message-signing keys natively via SIP-6 from HD keyring seeds instead of calling `@metamask/message-signing-snap` through `SnapController`. `AuthenticationController` and `UserStorageController` now require `KeyringController:withKeyringV2Unsafe` and no longer call `SnapController:handleRequest`. The message-signing snap remains for Portfolio / external origins ([#9824](https://github.com/MetaMask/core/pull/9824))
|
|
13
|
+
- Derive native SIP-6 keys with `@noble/hashes` HMAC-SHA-512 instead of Web Crypto, so auth works on React Native, whose SubtleCrypto cannot HMAC.
|
|
14
|
+
- Resolve HD entropy source IDs from `KeyringController` instead of the message-signing snap (`getBearerToken` primary ID, `performSignIn` SRP enumeration) ([#9794](https://github.com/MetaMask/core/pull/9794))
|
|
15
|
+
- Bump `@metamask/keyring-controller` from `^27.1.0` to `^27.1.1` ([#9791](https://github.com/MetaMask/core/pull/9791))
|
|
16
|
+
- Add `@metamask/key-tree` and `@noble/curves`; remove unused `@metamask/snaps-controllers`, `@metamask/snaps-sdk`, and `@metamask/snaps-utils` dependencies ([#9824](https://github.com/MetaMask/core/pull/9824))
|
|
14
17
|
|
|
15
18
|
## [29.0.0]
|
|
16
19
|
|
|
@@ -10,13 +10,14 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
|
|
|
10
10
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
11
11
|
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
12
12
|
};
|
|
13
|
-
var _AuthenticationController_instances, _AuthenticationController_metametrics, _AuthenticationController_auth, _AuthenticationController_config, _AuthenticationController_isUnlocked, _AuthenticationController_profilePairingRequestEpoch, _AuthenticationController_keyringController, _AuthenticationController_getLoginResponseFromState, _AuthenticationController_setLoginResponseToState, _AuthenticationController_assertIsUnlocked, _AuthenticationController_getHdKeyringEntropySourceIds, _AuthenticationController_getPrimaryEntropySourceId, _AuthenticationController_getLoginTag, _AuthenticationController_getLoginIdentifierType, _AuthenticationController_resolveSocialIdentifierType, _AuthenticationController_tryClearNeedsProfilePairing, _AuthenticationController_doPair, _AuthenticationController_pairSrpProfiles, _AuthenticationController_propagateCanonical, _AuthenticationController_getCanonicalProfileId, _AuthenticationController_invalidateSrpSession,
|
|
13
|
+
var _AuthenticationController_instances, _AuthenticationController_metametrics, _AuthenticationController_auth, _AuthenticationController_config, _AuthenticationController_isUnlocked, _AuthenticationController_profilePairingRequestEpoch, _AuthenticationController_keyringController, _AuthenticationController_getLoginResponseFromState, _AuthenticationController_setLoginResponseToState, _AuthenticationController_assertIsUnlocked, _AuthenticationController_getHdKeyringEntropySourceIds, _AuthenticationController_getPrimaryEntropySourceId, _AuthenticationController_getLoginTag, _AuthenticationController_getLoginIdentifierType, _AuthenticationController_resolveSocialIdentifierType, _AuthenticationController_tryClearNeedsProfilePairing, _AuthenticationController_doPair, _AuthenticationController_pairSrpProfiles, _AuthenticationController_propagateCanonical, _AuthenticationController_getCanonicalProfileId, _AuthenticationController_invalidateSrpSession, _AuthenticationController_getHdKeyringSeed, _AuthenticationController_getPublicKey, _AuthenticationController__signMessageCache, _AuthenticationController_scopedCacheKey, _AuthenticationController_signMessage;
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
exports.AuthenticationController = exports.defaultState = void 0;
|
|
16
16
|
const base_controller_1 = require("@metamask/base-controller");
|
|
17
17
|
const index_js_1 = require("../../sdk/index.cjs");
|
|
18
18
|
const entropy_source_js_1 = require("../../shared/utils/entropy-source.cjs");
|
|
19
|
-
const
|
|
19
|
+
const hd_keyring_seed_js_1 = require("../../shared/utils/hd-keyring-seed.cjs");
|
|
20
|
+
const message_signing_js_1 = require("../../shared/utils/message-signing.cjs");
|
|
20
21
|
const controllerName = 'AuthenticationController';
|
|
21
22
|
exports.defaultState = {
|
|
22
23
|
isSignedIn: false,
|
|
@@ -106,7 +107,7 @@ class AuthenticationController extends base_controller_1.BaseController {
|
|
|
106
107
|
});
|
|
107
108
|
},
|
|
108
109
|
});
|
|
109
|
-
|
|
110
|
+
_AuthenticationController__signMessageCache.set(this, {});
|
|
110
111
|
if (!metametrics) {
|
|
111
112
|
throw new Error('`metametrics` field is required');
|
|
112
113
|
}
|
|
@@ -125,8 +126,8 @@ class AuthenticationController extends base_controller_1.BaseController {
|
|
|
125
126
|
setLoginResponse: __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_setLoginResponseToState).bind(this),
|
|
126
127
|
},
|
|
127
128
|
signing: {
|
|
128
|
-
getIdentifier: __classPrivateFieldGet(this, _AuthenticationController_instances, "m",
|
|
129
|
-
signMessage: __classPrivateFieldGet(this, _AuthenticationController_instances, "m",
|
|
129
|
+
getIdentifier: __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getPublicKey).bind(this),
|
|
130
|
+
signMessage: __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_signMessage).bind(this),
|
|
130
131
|
},
|
|
131
132
|
getLoginTag: __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getLoginTag).bind(this),
|
|
132
133
|
getLoginIdentifierType: __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getLoginIdentifierType).bind(this),
|
|
@@ -268,7 +269,7 @@ class AuthenticationController extends base_controller_1.BaseController {
|
|
|
268
269
|
}
|
|
269
270
|
}
|
|
270
271
|
exports.AuthenticationController = AuthenticationController;
|
|
271
|
-
_AuthenticationController_metametrics = new WeakMap(), _AuthenticationController_auth = new WeakMap(), _AuthenticationController_config = new WeakMap(), _AuthenticationController_isUnlocked = new WeakMap(), _AuthenticationController_profilePairingRequestEpoch = new WeakMap(), _AuthenticationController_keyringController = new WeakMap(),
|
|
272
|
+
_AuthenticationController_metametrics = new WeakMap(), _AuthenticationController_auth = new WeakMap(), _AuthenticationController_config = new WeakMap(), _AuthenticationController_isUnlocked = new WeakMap(), _AuthenticationController_profilePairingRequestEpoch = new WeakMap(), _AuthenticationController_keyringController = new WeakMap(), _AuthenticationController__signMessageCache = new WeakMap(), _AuthenticationController_instances = new WeakSet(), _AuthenticationController_getLoginResponseFromState = async function _AuthenticationController_getLoginResponseFromState(entropySourceId) {
|
|
272
273
|
const resolvedId = entropySourceId ?? __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getPrimaryEntropySourceId).call(this);
|
|
273
274
|
if (!this.state.srpSessionData?.[resolvedId]) {
|
|
274
275
|
return null;
|
|
@@ -438,35 +439,51 @@ async function _AuthenticationController_doPair(accessTokens, epochAtStart) {
|
|
|
438
439
|
entry.profile.canonicalProfileId = '';
|
|
439
440
|
}
|
|
440
441
|
});
|
|
441
|
-
},
|
|
442
|
+
}, _AuthenticationController_getHdKeyringSeed =
|
|
442
443
|
/**
|
|
443
|
-
*
|
|
444
|
+
* Reads the BIP-39 seed for an HD entropy source from KeyringController.
|
|
445
|
+
*
|
|
446
|
+
* @param entropySourceId - Entropy source ID. Defaults to the primary HD
|
|
447
|
+
* keyring.
|
|
448
|
+
* @returns The HD keyring seed.
|
|
449
|
+
*/
|
|
450
|
+
async function _AuthenticationController_getHdKeyringSeed(entropySourceId) {
|
|
451
|
+
const resolvedId = entropySourceId ?? __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getPrimaryEntropySourceId).call(this);
|
|
452
|
+
return (0, hd_keyring_seed_js_1.getHdKeyringSeed)(this.messenger, resolvedId);
|
|
453
|
+
}, _AuthenticationController_getPublicKey =
|
|
454
|
+
/**
|
|
455
|
+
* Returns the message-signing public key via native SIP-6 derivation
|
|
456
|
+
* (same key as `@metamask/message-signing-snap` with empty salt).
|
|
444
457
|
*
|
|
445
458
|
* @param entropySourceId - The entropy source ID used to derive the key,
|
|
446
459
|
* when multiple sources are available (Multi-SRP).
|
|
447
|
-
* @returns The
|
|
460
|
+
* @returns The public key hex.
|
|
448
461
|
*/
|
|
449
|
-
async function
|
|
450
|
-
__classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#
|
|
451
|
-
const
|
|
452
|
-
return
|
|
453
|
-
},
|
|
462
|
+
async function _AuthenticationController_getPublicKey(entropySourceId) {
|
|
463
|
+
__classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#getPublicKey');
|
|
464
|
+
const seed = await __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getHdKeyringSeed).call(this, entropySourceId);
|
|
465
|
+
return (0, message_signing_js_1.getMessageSigningPublicKey)(seed);
|
|
466
|
+
}, _AuthenticationController_scopedCacheKey = function _AuthenticationController_scopedCacheKey(message, entropySourceId) {
|
|
467
|
+
return `${entropySourceId ?? __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getPrimaryEntropySourceId).call(this)}:${message}`;
|
|
468
|
+
}, _AuthenticationController_signMessage =
|
|
454
469
|
/**
|
|
455
|
-
* Signs a
|
|
470
|
+
* Signs a `metamask:…` message with the native SIP-6 message-signing key.
|
|
456
471
|
*
|
|
457
472
|
* @param message - A specific tagged message to sign.
|
|
458
473
|
* @param entropySourceId - The entropy source ID used to derive the key,
|
|
459
474
|
* when multiple sources are available (Multi-SRP).
|
|
460
|
-
* @returns
|
|
475
|
+
* @returns Compact secp256k1 signature hex.
|
|
461
476
|
*/
|
|
462
|
-
async function
|
|
477
|
+
async function _AuthenticationController_signMessage(message, entropySourceId) {
|
|
463
478
|
(0, index_js_1.assertMessageStartsWithMetamask)(message);
|
|
464
|
-
|
|
465
|
-
|
|
479
|
+
__classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#signMessage');
|
|
480
|
+
const cacheKey = __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_scopedCacheKey).call(this, message, entropySourceId);
|
|
481
|
+
if (__classPrivateFieldGet(this, _AuthenticationController__signMessageCache, "f")[cacheKey]) {
|
|
482
|
+
return __classPrivateFieldGet(this, _AuthenticationController__signMessageCache, "f")[cacheKey];
|
|
466
483
|
}
|
|
467
|
-
__classPrivateFieldGet(this, _AuthenticationController_instances, "m",
|
|
468
|
-
const result =
|
|
469
|
-
__classPrivateFieldGet(this,
|
|
484
|
+
const seed = await __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getHdKeyringSeed).call(this, entropySourceId);
|
|
485
|
+
const result = await (0, message_signing_js_1.signMessageWithMessageSigningKey)(message, seed);
|
|
486
|
+
__classPrivateFieldGet(this, _AuthenticationController__signMessageCache, "f")[cacheKey] = result;
|
|
470
487
|
return result;
|
|
471
488
|
};
|
|
472
489
|
//# sourceMappingURL=AuthenticationController.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthenticationController.cjs","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,+DAA2D;AAyB3D,kDAK4B;AAE5B,6EAG8C;AAC9C,oEAGiC;AAGjC,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAmBrC,QAAA,YAAY,GAAkC;IACzD,UAAU,EAAE,KAAK;IACjB,mBAAmB,EAAE,IAAI;CAC1B,CAAC;AACF,MAAM,QAAQ,GAAiD;IAC7D,UAAU,EAAE;QACV,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,mBAAmB,EAAE;QACnB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,cAAc,EAAE;QACd,sCAAsC;QACtC,kBAAkB,EAAE,CAAC,cAAc,EAAE,EAAE;YACrC,4FAA4F;YAC5F,2FAA2F;YAC3F,mEAAmE;YACnE,kEAAkE;YAClE,oDAAoD;YACpD,IAAI,cAAc,KAAK,IAAI,IAAI,cAAc,KAAK,SAAS,EAAE,CAAC;gBAC5D,OAAO,IAAI,CAAC;YACd,CAAC;YACD,OAAO,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,MAAM,CAC1C,CAAC,uBAAuB,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;gBACxC,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,GAAG,uBAAuB,EAAE,GACxD,KAAK,CAAC,KAAK,CAAC;gBACd,uBAAuB,CAAC,GAAG,CAAC,GAAG;oBAC7B,GAAG,KAAK;oBACR,K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uDAAuB,CAAC,OAAO,CAAC,EAAE,CAAC;QACzC,OAAO,uBAAA,IAAI,uDAAuB,CAAC,OAAO,CAAC,CAAC;IAC9C,CAAC;IAED,uBAAA,IAAI,uFAAkB,MAAtB,IAAI,EAAmB,kBAAkB,CAAC,CAAC;IAE3C,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CACvC,8BAA8B,EAC9B,IAAA,oDAA4B,EAAC,OAAO,EAAE,eAAe,CAAC,CACvD,CAAW,CAAC;IAEb,uBAAA,IAAI,uDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\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 { SeedlessOnboardingControllerGetStateAction } from '@metamask/seedless-onboarding-controller';\nimport type { SnapControllerHandleRequestAction } from '@metamask/snaps-controllers';\nimport type { Json } from '@metamask/utils';\n\nimport type {\n LoginIdentifierType,\n LoginResponse,\n ProfileAlias,\n SRPInterface,\n SrpLoginTag,\n UserProfile,\n UserProfileLineage,\n} from '../../sdk/index.js';\nimport {\n assertMessageStartsWithMetamask,\n AuthType,\n Env,\n JwtBearerAuth,\n} from '../../sdk/index.js';\nimport type { MetaMetricsAuth } from '../../shared/types/services.js';\nimport {\n getHdKeyringEntropySourceIds,\n getPrimaryHdKeyringEntropySourceId,\n} from '../../shared/utils/entropy-source.js';\nimport {\n createSnapPublicKeyRequest,\n createSnapSignMessageRequest,\n} from './auth-snap-requests.js';\nimport { AuthenticationControllerMethodActions } from './AuthenticationController-method-action-types.js';\n\nconst controllerName = 'AuthenticationController';\n\n// State\nexport type AuthenticationControllerState = {\n isSignedIn: boolean;\n srpSessionData?: Record<string, LoginResponse>;\n /**\n * Client gate for profile pairing. Defaults to `true` (fresh install /\n * upgrade), set to `false` after a successful `performSignIn` pair, set\n * back to `true` via `requestProfilePairing()` when the SRP set changes,\n * and left `true` on pair failure so the next state shift retries.\n *\n * Optional in the type so partial-state selectors stay assignable to\n * `AuthenticationControllerState`. The controller seeds it via\n * `defaultState` at construction; consumers should read `undefined` as\n * `true` to mirror that runtime default.\n */\n needsProfilePairing?: boolean;\n};\nexport const defaultState: AuthenticationControllerState = {\n isSignedIn: false,\n needsProfilePairing: true,\n};\nconst metadata: StateMetadata<AuthenticationControllerState> = {\n isSignedIn: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n needsProfilePairing: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n srpSessionData: {\n // Remove access token from state logs\n includeInStateLogs: (srpSessionData) => {\n // Unreachable branch, included just to fix a type error for the case where this property is\n // unset. The type gets collapsed to include `| undefined` even though `undefined` is never\n // set here, because we don't yet use `exactOptionalPropertyTypes`.\n // TODO: Remove branch after enabling `exactOptionalPropertyTypes`\n // ref: https://github.com/MetaMask/core/issues/6565\n if (srpSessionData === null || srpSessionData === undefined) {\n return null;\n }\n return Object.entries(srpSessionData).reduce<Record<string, Json>>(\n (sanitizedSrpSessionData, [key, value]) => {\n const { accessToken: _unused, ...tokenWithoutAccessToken } =\n value.token;\n sanitizedSrpSessionData[key] = {\n ...value,\n token: tokenWithoutAccessToken,\n };\n return sanitizedSrpSessionData;\n },\n {},\n );\n },\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\ntype ControllerConfig = {\n env: Env;\n};\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'performSignIn',\n 'performSignOut',\n 'getBearerToken',\n 'getSessionProfile',\n 'refreshCanonicalProfileId',\n 'getUserProfileLineage',\n 'getCustomerServiceToken',\n 'isSignedIn',\n 'requestProfilePairing',\n] as const;\n\nexport type Actions =\n | AuthenticationControllerGetStateAction\n | AuthenticationControllerMethodActions;\n\nexport type AuthenticationControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n AuthenticationControllerState\n>;\n\nexport type AuthenticationControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n AuthenticationControllerState\n >;\n\nexport type ProfileSignInInfo = {\n profileId: string;\n profileAliases: ProfileAlias[];\n profileIdChanged: boolean;\n};\n\nexport type AuthenticationControllerProfileSignInEvent = {\n type: `${typeof controllerName}:profileSignIn`;\n payload: [ProfileSignInInfo];\n};\n\nexport type Events =\n | AuthenticationControllerStateChangeEvent\n | AuthenticationControllerProfileSignInEvent;\n\n// Allowed Actions\ntype AllowedActions =\n | KeyringControllerGetStateAction\n | SnapControllerHandleRequestAction\n | SeedlessOnboardingControllerGetStateAction;\n\ntype AllowedEvents = KeyringControllerLockEvent | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type AuthenticationControllerMessenger = Messenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents\n>;\n\n/**\n * Controller that enables authentication for restricted endpoints.\n * Used for Backup & Sync, Notifications, and other services.\n */\nexport class AuthenticationController extends BaseController<\n typeof controllerName,\n AuthenticationControllerState,\n AuthenticationControllerMessenger\n> {\n readonly #metametrics: MetaMetricsAuth;\n\n readonly #auth: SRPInterface;\n\n readonly #config: ControllerConfig = {\n env: Env.PRD,\n };\n\n #isUnlocked = false;\n\n // Bumped by `requestProfilePairing`. `performSignIn` snapshots this\n // before its first await; if it changes mid-flight we must NOT clear\n // `needsProfilePairing` (the rearm signal wins).\n #profilePairingRequestEpoch = 0;\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messenger.call('KeyringController:getState');\n this.#isUnlocked = isUnlocked;\n\n this.messenger.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messenger.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n constructor({\n messenger,\n state,\n config,\n metametrics,\n }: {\n messenger: AuthenticationControllerMessenger;\n state?: AuthenticationControllerState;\n config?: Partial<ControllerConfig>;\n /**\n * Not using the Messaging System as we\n * do not want to tie this strictly to extension\n */\n metametrics: MetaMetricsAuth;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n if (!metametrics) {\n throw new Error('`metametrics` field is required');\n }\n\n this.#config = {\n ...this.#config,\n ...config,\n };\n\n this.#metametrics = metametrics;\n\n this.#auth = new JwtBearerAuth(\n {\n env: this.#config.env,\n platform: metametrics.agent,\n type: AuthType.SRP,\n },\n {\n storage: {\n getLoginResponse: this.#getLoginResponseFromState.bind(this),\n setLoginResponse: this.#setLoginResponseToState.bind(this),\n },\n signing: {\n getIdentifier: this.#snapGetPublicKey.bind(this),\n signMessage: this.#snapSignMessage.bind(this),\n },\n getLoginTag: this.#getLoginTag.bind(this),\n getLoginIdentifierType: this.#getLoginIdentifierType.bind(this),\n metametrics: this.#metametrics,\n },\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n async #getLoginResponseFromState(\n entropySourceId?: string,\n ): Promise<LoginResponse | null> {\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n if (!this.state.srpSessionData?.[resolvedId]) {\n return null;\n }\n return this.state.srpSessionData[resolvedId];\n }\n\n async #setLoginResponseToState(\n loginResponse: LoginResponse,\n entropySourceId?: string,\n ) {\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n const metaMetricsId = await this.#metametrics.getMetaMetricsId();\n this.update((state) => {\n state.isSignedIn = true;\n if (!state.srpSessionData) {\n state.srpSessionData = {};\n }\n state.srpSessionData[resolvedId] = {\n ...loginResponse,\n profile: {\n ...loginResponse.profile,\n metaMetricsId,\n },\n };\n });\n }\n\n #assertIsUnlocked(methodName: string): void {\n if (!this.#isUnlocked) {\n throw new Error(`${methodName} - unable to proceed, wallet is locked`);\n }\n }\n\n /**\n * Reads the HD keyring entropy source IDs from KeyringController.\n *\n * @returns The HD keyring metadata IDs, primary first.\n */\n #getHdKeyringEntropySourceIds(): string[] {\n const { keyrings } = this.messenger.call('KeyringController:getState');\n return getHdKeyringEntropySourceIds(keyrings);\n }\n\n /**\n * Resolves the primary SRP's entropy source ID from KeyringController rather\n * than the message-signing snap, so callers like `getBearerToken()` are not\n * blocked on snap boot.\n *\n * @returns The primary HD keyring metadata ID.\n * @throws If no HD keyring is available; callers must only resolve while\n * the wallet is unlocked.\n */\n #getPrimaryEntropySourceId(): string {\n const { keyrings } = this.messenger.call('KeyringController:getState');\n return getPrimaryHdKeyringEntropySourceId(keyrings);\n }\n\n /**\n * Resolves the SRP login tag for `raw_message`.\n *\n * - `primary` for the first HD entropy source\n * - `secondary` for any other entropy source\n *\n * @param entropySourceId - Entropy source for this login attempt.\n * @returns The login tag to append to the signed message.\n */\n async #getLoginTag(entropySourceId?: string): Promise<SrpLoginTag> {\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n const resolvedId = entropySourceId ?? primaryEntropySourceId;\n\n return resolvedId === primaryEntropySourceId ? 'primary' : 'secondary';\n }\n\n /**\n * Resolves metametrics `identifier_type` for `/srp/login`\n * (`SRP` | `GOOGLE` | `APPLE` | `TELEGRAM`).\n *\n * This is the auth method for the entropy source, independent of\n * {@link SrpLoginTag} (`primary` / `secondary`).\n *\n * SeedlessOnboarding currently exposes a single vault-level\n * `authConnection`, which always backs the primary entropy source. Non-\n * primary sources therefore return `SRP`. If social identities become\n * per-entropy later, resolve from that metadata instead of assuming\n * primary === social.\n *\n * Soft-fails to `SRP` when SeedlessOnboarding is not registered.\n *\n * @param entropySourceId - Entropy source for this login attempt.\n * @returns The login identifier type.\n */\n async #getLoginIdentifierType(\n entropySourceId?: string,\n ): Promise<LoginIdentifierType> {\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n const resolvedId = entropySourceId ?? primaryEntropySourceId;\n\n // Social vault authConnection is only associated with the primary source.\n if (resolvedId !== primaryEntropySourceId) {\n return 'SRP';\n }\n\n return this.#resolveSocialIdentifierType();\n }\n\n /**\n * Maps `SeedlessOnboardingController.state.authConnection` to a login\n * identifier type when a social vault is present.\n *\n * Returns `SRP` if there is no vault, the provider is unrecognized, or\n * SeedlessOnboardingController is unavailable on the messenger.\n *\n * @returns The social provider identifier type, or `SRP`.\n */\n #resolveSocialIdentifierType(): LoginIdentifierType {\n try {\n const { vault, authConnection } = this.messenger.call(\n 'SeedlessOnboardingController:getState',\n );\n if (vault === null || vault === undefined) {\n return 'SRP';\n }\n\n // Match provider strings from SeedlessOnboarding state rather than\n // importing AuthConnection — a value import would load that package\n // (and its heavy deps) whenever this controller is imported.\n switch (authConnection) {\n case 'google':\n return 'GOOGLE';\n case 'apple':\n return 'APPLE';\n case 'telegram':\n return 'TELEGRAM';\n default:\n return 'SRP';\n }\n } catch {\n return 'SRP';\n }\n }\n\n public async performSignIn(): Promise<string[]> {\n this.#assertIsUnlocked('performSignIn');\n\n const epochAtStart = this.#profilePairingRequestEpoch;\n const entropySourceIds = this.#getHdKeyringEntropySourceIds();\n const accessTokens: string[] = [];\n\n // We iterate sequentially in order to be sure that the first entry\n // is the primary SRP LoginResponse.\n for (const entropySourceId of entropySourceIds) {\n const accessToken = await this.#auth.getAccessToken(entropySourceId);\n accessTokens.push(accessToken);\n }\n\n if (entropySourceIds.length < 2) {\n // Single-SRP wallet: nothing to pair.\n this.#tryClearNeedsProfilePairing(epochAtStart);\n } else {\n // Pair failures must not break sign-in; the gate stays `true` for retry.\n try {\n await this.#doPair(accessTokens, epochAtStart);\n } catch {\n // noop\n }\n }\n\n return accessTokens;\n }\n\n /**\n * Marks profile pairing as needed. Clients call this when the SRP set\n * changes (e.g. a new keyring was added) so the next auto-sign-in cycle\n * re-runs `performSignIn` and re-pairs.\n */\n public requestProfilePairing(): void {\n this.#profilePairingRequestEpoch += 1;\n if (!this.state.needsProfilePairing) {\n this.update((state) => {\n state.needsProfilePairing = true;\n });\n }\n }\n\n /**\n * Clears `needsProfilePairing` only if no `requestProfilePairing` call\n * landed since `epochAtStart` was captured. Prevents `performSignIn`\n * from silently overwriting a concurrent rearm.\n *\n * @param epochAtStart - Epoch value captured at the start of `performSignIn`.\n */\n #tryClearNeedsProfilePairing(epochAtStart: number): void {\n if (this.#profilePairingRequestEpoch !== epochAtStart) {\n return;\n }\n if (this.state.needsProfilePairing) {\n this.update((state) => {\n state.needsProfilePairing = false;\n });\n }\n }\n\n /**\n * Pairs all SRPs via `POST /profile/pair`, propagates the canonical\n * profile ID, clears `needsProfilePairing`, and emits\n * `AuthenticationController:profileSignIn` when the canonical changes or\n * new aliases are returned. Throws on failure.\n *\n * @param accessTokens - Per-SRP access tokens, primary first.\n * @param epochAtStart - Pairing-request epoch captured by the caller.\n * Used to skip the gate clear if `requestProfilePairing` ran while the\n * pair API call was in-flight.\n */\n async #doPair(accessTokens: string[], epochAtStart: number): Promise<void> {\n const previousCanonical = this.#getCanonicalProfileId();\n\n const profileAliases = await this.#pairSrpProfiles(accessTokens);\n const newCanonical = this.#getCanonicalProfileId();\n\n // If somehow we cannot compute the new canonical profile ID after pairing,\n // we just return now and do not update the `needsProfilePairing` flag.\n if (!newCanonical) {\n return;\n }\n\n this.#tryClearNeedsProfilePairing(epochAtStart);\n\n const profileIdChanged = previousCanonical !== newCanonical;\n const shouldEmitProfileSignInEvent =\n profileIdChanged || profileAliases.length > 0;\n\n if (shouldEmitProfileSignInEvent) {\n this.messenger.publish('AuthenticationController:profileSignIn', {\n profileId: newCanonical,\n profileAliases,\n profileIdChanged,\n });\n }\n }\n\n async #pairSrpProfiles(accessTokens: string[]): Promise<ProfileAlias[]> {\n if (accessTokens.length < 2) {\n return [];\n }\n const primaryAccessToken = accessTokens[0]; // Associated with primary SRP.\n const {\n profileAliases,\n profile: { canonicalProfileId },\n } = await this.#auth.pairSrpProfiles(accessTokens, primaryAccessToken);\n this.#propagateCanonical(canonicalProfileId);\n return profileAliases;\n }\n\n #propagateCanonical(canonicalProfileId: string): void {\n const { srpSessionData } = this.state;\n if (!srpSessionData) {\n return;\n }\n\n this.update((state) => {\n for (const entry of Object.values(state.srpSessionData ?? {})) {\n if (entry?.profile) {\n entry.profile.canonicalProfileId = canonicalProfileId;\n }\n }\n });\n }\n\n /**\n * Returns the canonical profile id from the primary SRP's cached session.\n * Returns `null` when no session exists yet for the primary SRP.\n *\n * Always reads from the primary SRP because the canonical is shared across\n * all paired SRPs after `#propagateCanonical`.\n *\n * @returns The canonical profile id, or `null` if unavailable.\n */\n #getCanonicalProfileId(): string | null {\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n return (\n this.state.srpSessionData?.[primaryEntropySourceId]?.profile\n ?.canonicalProfileId ?? null\n );\n }\n\n public performSignOut(): void {\n this.update((state) => {\n state.isSignedIn = false;\n state.srpSessionData = undefined;\n });\n }\n\n /**\n * Returns a bearer token for the specified SRP, logging in if needed.\n *\n * When called without `entropySourceId`, returns the primary (first) SRP's\n * access token, which is effectively the canonical\n * profile's token that can be used by alias-aware consumers for cross-SRP\n * operations.\n *\n * @param entropySourceId - The entropy source ID. Omit for the primary SRP.\n * @returns The OIDC access token.\n */\n public async getBearerToken(entropySourceId?: string): Promise<string> {\n this.#assertIsUnlocked('getBearerToken');\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n return await this.#auth.getAccessToken(resolvedId);\n }\n\n /**\n * Returns the cached session profile, logging in if no session exists.\n *\n * The returned `canonicalProfileId` reflects the value from the most recent\n * login or pairing. In the rare event where a canonical changed because of\n * a pairing that happened on another device, the cached value may be stale\n * until the next login. For guaranteed freshness, call\n * `refreshCanonicalProfileId()` before reading `canonicalProfileId`.\n *\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns profile for the session.\n */\n public async getSessionProfile(\n entropySourceId?: string,\n ): Promise<UserProfile> {\n this.#assertIsUnlocked('getSessionProfile');\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n return await this.#auth.getUserProfile(resolvedId);\n }\n\n /**\n * Forces a fresh retrieval of the canonical profile ID from the server\n * and propagates it to all cached SRP sessions.\n *\n * This method invalidates the primary SRP's cached session and forces a\n * re-login. Use it before operations that require a guaranteed-fresh\n * canonical (e.g. storage key derivation for Accounts ADR 0005). For\n * best-effort reads, use\n * `getSessionProfile().canonicalProfileId` instead.\n *\n * Only the primary SRP is re-logged-in regardless of how many SRPs exist —\n * the server returns the current canonical for the entire pairing group\n * from any single SRP login.\n *\n * @returns The refreshed canonical profile ID.\n */\n public async refreshCanonicalProfileId(): Promise<string> {\n this.#assertIsUnlocked('refreshCanonicalProfileId');\n\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n this.#invalidateSrpSession(primaryEntropySourceId);\n await this.#auth.getAccessToken(primaryEntropySourceId);\n\n const canonical = this.#getCanonicalProfileId();\n if (!canonical) {\n throw new Error(\n 'refreshCanonicalProfileId - Unable to resolve canonical profile ID',\n );\n }\n\n this.#propagateCanonical(canonical);\n return canonical;\n }\n\n #invalidateSrpSession(entropySourceId: string): void {\n this.update((state) => {\n const entry = state.srpSessionData?.[entropySourceId];\n if (entry?.profile) {\n // Setting canonicalProfileId to '' forces a re-fetch on the next\n // #getAuthSession call. The falsy check (!auth.profile.canonicalProfileId)\n // treats '' the same as undefined/null — all signal an invalid session.\n entry.profile.canonicalProfileId = '';\n }\n });\n }\n\n public async getUserProfileLineage(\n entropySourceId?: string,\n ): Promise<UserProfileLineage> {\n this.#assertIsUnlocked('getUserProfileLineage');\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n return await this.#auth.getUserProfileLineage(resolvedId);\n }\n\n /**\n * Returns a Customer Service specific access token for the specified SRP,\n * logging in if needed.\n *\n * Exchanges the OIDC access token for a short-lived token scoped to the\n * customer-service audience. Customer Service tooling consumes this token to\n * identify and authenticate the user.\n *\n * @param entropySourceId - The entropy source ID. Omit for the primary SRP.\n * @returns The customer-service access token.\n */\n public async getCustomerServiceToken(\n entropySourceId?: string,\n ): Promise<string> {\n this.#assertIsUnlocked('getCustomerServiceToken');\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n return await this.#auth.getCustomerServiceToken(resolvedId);\n }\n\n public isSignedIn(): boolean {\n return this.state.isSignedIn;\n }\n\n /**\n * Returns the auth snap public key.\n *\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns The snap public key.\n */\n async #snapGetPublicKey(entropySourceId?: string): Promise<string> {\n this.#assertIsUnlocked('#snapGetPublicKey');\n\n const result = (await this.messenger.call(\n 'SnapController:handleRequest',\n createSnapPublicKeyRequest(entropySourceId),\n )) as string;\n\n return result;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(\n message: string,\n entropySourceId?: string,\n ): Promise<string> {\n assertMessageStartsWithMetamask(message);\n\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n this.#assertIsUnlocked('#snapSignMessage');\n\n const result = (await this.messenger.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message, entropySourceId),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"AuthenticationController.cjs","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,+DAA2D;AAyB3D,kDAK4B;AAE5B,6EAG8C;AAC9C,+EAAyE;AACzE,+EAG+C;AAG/C,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAmBrC,QAAA,YAAY,G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EAAmB,cAAc,CAAC,CAAC;IAEvC,MAAM,QAAQ,GAAG,uBAAA,IAAI,qFAAgB,MAApB,IAAI,EAAiB,OAAO,EAAE,eAAe,CAAC,CAAC;IAChE,IAAI,uBAAA,IAAI,mDAAmB,CAAC,QAAQ,CAAC,EAAE,CAAC;QACtC,OAAO,uBAAA,IAAI,mDAAmB,CAAC,QAAQ,CAAC,CAAC;IAC3C,CAAC;IAED,MAAM,IAAI,GAAG,MAAM,uBAAA,IAAI,uFAAkB,MAAtB,IAAI,EAAmB,eAAe,CAAC,CAAC;IAC3D,MAAM,MAAM,GAAG,MAAM,IAAA,qDAAgC,EAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAErE,uBAAA,IAAI,mDAAmB,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC;IAE3C,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n KeyringControllerWithKeyringV2UnsafeAction,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { SeedlessOnboardingControllerGetStateAction } from '@metamask/seedless-onboarding-controller';\nimport type { Json } from '@metamask/utils';\n\nimport type {\n LoginIdentifierType,\n LoginResponse,\n ProfileAlias,\n SRPInterface,\n SrpLoginTag,\n UserProfile,\n UserProfileLineage,\n} from '../../sdk/index.js';\nimport {\n assertMessageStartsWithMetamask,\n AuthType,\n Env,\n JwtBearerAuth,\n} from '../../sdk/index.js';\nimport type { MetaMetricsAuth } from '../../shared/types/services.js';\nimport {\n getHdKeyringEntropySourceIds,\n getPrimaryHdKeyringEntropySourceId,\n} from '../../shared/utils/entropy-source.js';\nimport { getHdKeyringSeed } from '../../shared/utils/hd-keyring-seed.js';\nimport {\n getMessageSigningPublicKey,\n signMessageWithMessageSigningKey,\n} from '../../shared/utils/message-signing.js';\nimport { AuthenticationControllerMethodActions } from './AuthenticationController-method-action-types.js';\n\nconst controllerName = 'AuthenticationController';\n\n// State\nexport type AuthenticationControllerState = {\n isSignedIn: boolean;\n srpSessionData?: Record<string, LoginResponse>;\n /**\n * Client gate for profile pairing. Defaults to `true` (fresh install /\n * upgrade), set to `false` after a successful `performSignIn` pair, set\n * back to `true` via `requestProfilePairing()` when the SRP set changes,\n * and left `true` on pair failure so the next state shift retries.\n *\n * Optional in the type so partial-state selectors stay assignable to\n * `AuthenticationControllerState`. The controller seeds it via\n * `defaultState` at construction; consumers should read `undefined` as\n * `true` to mirror that runtime default.\n */\n needsProfilePairing?: boolean;\n};\nexport const defaultState: AuthenticationControllerState = {\n isSignedIn: false,\n needsProfilePairing: true,\n};\nconst metadata: StateMetadata<AuthenticationControllerState> = {\n isSignedIn: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n needsProfilePairing: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n srpSessionData: {\n // Remove access token from state logs\n includeInStateLogs: (srpSessionData) => {\n // Unreachable branch, included just to fix a type error for the case where this property is\n // unset. The type gets collapsed to include `| undefined` even though `undefined` is never\n // set here, because we don't yet use `exactOptionalPropertyTypes`.\n // TODO: Remove branch after enabling `exactOptionalPropertyTypes`\n // ref: https://github.com/MetaMask/core/issues/6565\n if (srpSessionData === null || srpSessionData === undefined) {\n return null;\n }\n return Object.entries(srpSessionData).reduce<Record<string, Json>>(\n (sanitizedSrpSessionData, [key, value]) => {\n const { accessToken: _unused, ...tokenWithoutAccessToken } =\n value.token;\n sanitizedSrpSessionData[key] = {\n ...value,\n token: tokenWithoutAccessToken,\n };\n return sanitizedSrpSessionData;\n },\n {},\n );\n },\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\ntype ControllerConfig = {\n env: Env;\n};\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'performSignIn',\n 'performSignOut',\n 'getBearerToken',\n 'getSessionProfile',\n 'refreshCanonicalProfileId',\n 'getUserProfileLineage',\n 'getCustomerServiceToken',\n 'isSignedIn',\n 'requestProfilePairing',\n] as const;\n\nexport type Actions =\n | AuthenticationControllerGetStateAction\n | AuthenticationControllerMethodActions;\n\nexport type AuthenticationControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n AuthenticationControllerState\n>;\n\nexport type AuthenticationControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n AuthenticationControllerState\n >;\n\nexport type ProfileSignInInfo = {\n profileId: string;\n profileAliases: ProfileAlias[];\n profileIdChanged: boolean;\n};\n\nexport type AuthenticationControllerProfileSignInEvent = {\n type: `${typeof controllerName}:profileSignIn`;\n payload: [ProfileSignInInfo];\n};\n\nexport type Events =\n | AuthenticationControllerStateChangeEvent\n | AuthenticationControllerProfileSignInEvent;\n\n// Allowed Actions\ntype AllowedActions =\n | KeyringControllerGetStateAction\n | KeyringControllerWithKeyringV2UnsafeAction\n | SeedlessOnboardingControllerGetStateAction;\n\ntype AllowedEvents = KeyringControllerLockEvent | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type AuthenticationControllerMessenger = Messenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents\n>;\n\n/**\n * Controller that enables authentication for restricted endpoints.\n * Used for Backup & Sync, Notifications, and other services.\n */\nexport class AuthenticationController extends BaseController<\n typeof controllerName,\n AuthenticationControllerState,\n AuthenticationControllerMessenger\n> {\n readonly #metametrics: MetaMetricsAuth;\n\n readonly #auth: SRPInterface;\n\n readonly #config: ControllerConfig = {\n env: Env.PRD,\n };\n\n #isUnlocked = false;\n\n // Bumped by `requestProfilePairing`. `performSignIn` snapshots this\n // before its first await; if it changes mid-flight we must NOT clear\n // `needsProfilePairing` (the rearm signal wins).\n #profilePairingRequestEpoch = 0;\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messenger.call('KeyringController:getState');\n this.#isUnlocked = isUnlocked;\n\n this.messenger.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messenger.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n constructor({\n messenger,\n state,\n config,\n metametrics,\n }: {\n messenger: AuthenticationControllerMessenger;\n state?: AuthenticationControllerState;\n config?: Partial<ControllerConfig>;\n /**\n * Not using the Messaging System as we\n * do not want to tie this strictly to extension\n */\n metametrics: MetaMetricsAuth;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n if (!metametrics) {\n throw new Error('`metametrics` field is required');\n }\n\n this.#config = {\n ...this.#config,\n ...config,\n };\n\n this.#metametrics = metametrics;\n\n this.#auth = new JwtBearerAuth(\n {\n env: this.#config.env,\n platform: metametrics.agent,\n type: AuthType.SRP,\n },\n {\n storage: {\n getLoginResponse: this.#getLoginResponseFromState.bind(this),\n setLoginResponse: this.#setLoginResponseToState.bind(this),\n },\n signing: {\n getIdentifier: this.#getPublicKey.bind(this),\n signMessage: this.#signMessage.bind(this),\n },\n getLoginTag: this.#getLoginTag.bind(this),\n getLoginIdentifierType: this.#getLoginIdentifierType.bind(this),\n metametrics: this.#metametrics,\n },\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n async #getLoginResponseFromState(\n entropySourceId?: string,\n ): Promise<LoginResponse | null> {\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n if (!this.state.srpSessionData?.[resolvedId]) {\n return null;\n }\n return this.state.srpSessionData[resolvedId];\n }\n\n async #setLoginResponseToState(\n loginResponse: LoginResponse,\n entropySourceId?: string,\n ) {\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n const metaMetricsId = await this.#metametrics.getMetaMetricsId();\n this.update((state) => {\n state.isSignedIn = true;\n if (!state.srpSessionData) {\n state.srpSessionData = {};\n }\n state.srpSessionData[resolvedId] = {\n ...loginResponse,\n profile: {\n ...loginResponse.profile,\n metaMetricsId,\n },\n };\n });\n }\n\n #assertIsUnlocked(methodName: string): void {\n if (!this.#isUnlocked) {\n throw new Error(`${methodName} - unable to proceed, wallet is locked`);\n }\n }\n\n /**\n * Reads the HD keyring entropy source IDs from KeyringController.\n *\n * @returns The HD keyring metadata IDs, primary first.\n */\n #getHdKeyringEntropySourceIds(): string[] {\n const { keyrings } = this.messenger.call('KeyringController:getState');\n return getHdKeyringEntropySourceIds(keyrings);\n }\n\n /**\n * Resolves the primary SRP's entropy source ID from KeyringController rather\n * than the message-signing snap, so callers like `getBearerToken()` are not\n * blocked on snap boot.\n *\n * @returns The primary HD keyring metadata ID.\n * @throws If no HD keyring is available; callers must only resolve while\n * the wallet is unlocked.\n */\n #getPrimaryEntropySourceId(): string {\n const { keyrings } = this.messenger.call('KeyringController:getState');\n return getPrimaryHdKeyringEntropySourceId(keyrings);\n }\n\n /**\n * Resolves the SRP login tag for `raw_message`.\n *\n * - `primary` for the first HD entropy source\n * - `secondary` for any other entropy source\n *\n * @param entropySourceId - Entropy source for this login attempt.\n * @returns The login tag to append to the signed message.\n */\n async #getLoginTag(entropySourceId?: string): Promise<SrpLoginTag> {\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n const resolvedId = entropySourceId ?? primaryEntropySourceId;\n\n return resolvedId === primaryEntropySourceId ? 'primary' : 'secondary';\n }\n\n /**\n * Resolves metametrics `identifier_type` for `/srp/login`\n * (`SRP` | `GOOGLE` | `APPLE` | `TELEGRAM`).\n *\n * This is the auth method for the entropy source, independent of\n * {@link SrpLoginTag} (`primary` / `secondary`).\n *\n * SeedlessOnboarding currently exposes a single vault-level\n * `authConnection`, which always backs the primary entropy source. Non-\n * primary sources therefore return `SRP`. If social identities become\n * per-entropy later, resolve from that metadata instead of assuming\n * primary === social.\n *\n * Soft-fails to `SRP` when SeedlessOnboarding is not registered.\n *\n * @param entropySourceId - Entropy source for this login attempt.\n * @returns The login identifier type.\n */\n async #getLoginIdentifierType(\n entropySourceId?: string,\n ): Promise<LoginIdentifierType> {\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n const resolvedId = entropySourceId ?? primaryEntropySourceId;\n\n // Social vault authConnection is only associated with the primary source.\n if (resolvedId !== primaryEntropySourceId) {\n return 'SRP';\n }\n\n return this.#resolveSocialIdentifierType();\n }\n\n /**\n * Maps `SeedlessOnboardingController.state.authConnection` to a login\n * identifier type when a social vault is present.\n *\n * Returns `SRP` if there is no vault, the provider is unrecognized, or\n * SeedlessOnboardingController is unavailable on the messenger.\n *\n * @returns The social provider identifier type, or `SRP`.\n */\n #resolveSocialIdentifierType(): LoginIdentifierType {\n try {\n const { vault, authConnection } = this.messenger.call(\n 'SeedlessOnboardingController:getState',\n );\n if (vault === null || vault === undefined) {\n return 'SRP';\n }\n\n // Match provider strings from SeedlessOnboarding state rather than\n // importing AuthConnection — a value import would load that package\n // (and its heavy deps) whenever this controller is imported.\n switch (authConnection) {\n case 'google':\n return 'GOOGLE';\n case 'apple':\n return 'APPLE';\n case 'telegram':\n return 'TELEGRAM';\n default:\n return 'SRP';\n }\n } catch {\n return 'SRP';\n }\n }\n\n public async performSignIn(): Promise<string[]> {\n this.#assertIsUnlocked('performSignIn');\n\n const epochAtStart = this.#profilePairingRequestEpoch;\n const entropySourceIds = this.#getHdKeyringEntropySourceIds();\n const accessTokens: string[] = [];\n\n // We iterate sequentially in order to be sure that the first entry\n // is the primary SRP LoginResponse.\n for (const entropySourceId of entropySourceIds) {\n const accessToken = await this.#auth.getAccessToken(entropySourceId);\n accessTokens.push(accessToken);\n }\n\n if (entropySourceIds.length < 2) {\n // Single-SRP wallet: nothing to pair.\n this.#tryClearNeedsProfilePairing(epochAtStart);\n } else {\n // Pair failures must not break sign-in; the gate stays `true` for retry.\n try {\n await this.#doPair(accessTokens, epochAtStart);\n } catch {\n // noop\n }\n }\n\n return accessTokens;\n }\n\n /**\n * Marks profile pairing as needed. Clients call this when the SRP set\n * changes (e.g. a new keyring was added) so the next auto-sign-in cycle\n * re-runs `performSignIn` and re-pairs.\n */\n public requestProfilePairing(): void {\n this.#profilePairingRequestEpoch += 1;\n if (!this.state.needsProfilePairing) {\n this.update((state) => {\n state.needsProfilePairing = true;\n });\n }\n }\n\n /**\n * Clears `needsProfilePairing` only if no `requestProfilePairing` call\n * landed since `epochAtStart` was captured. Prevents `performSignIn`\n * from silently overwriting a concurrent rearm.\n *\n * @param epochAtStart - Epoch value captured at the start of `performSignIn`.\n */\n #tryClearNeedsProfilePairing(epochAtStart: number): void {\n if (this.#profilePairingRequestEpoch !== epochAtStart) {\n return;\n }\n if (this.state.needsProfilePairing) {\n this.update((state) => {\n state.needsProfilePairing = false;\n });\n }\n }\n\n /**\n * Pairs all SRPs via `POST /profile/pair`, propagates the canonical\n * profile ID, clears `needsProfilePairing`, and emits\n * `AuthenticationController:profileSignIn` when the canonical changes or\n * new aliases are returned. Throws on failure.\n *\n * @param accessTokens - Per-SRP access tokens, primary first.\n * @param epochAtStart - Pairing-request epoch captured by the caller.\n * Used to skip the gate clear if `requestProfilePairing` ran while the\n * pair API call was in-flight.\n */\n async #doPair(accessTokens: string[], epochAtStart: number): Promise<void> {\n const previousCanonical = this.#getCanonicalProfileId();\n\n const profileAliases = await this.#pairSrpProfiles(accessTokens);\n const newCanonical = this.#getCanonicalProfileId();\n\n // If somehow we cannot compute the new canonical profile ID after pairing,\n // we just return now and do not update the `needsProfilePairing` flag.\n if (!newCanonical) {\n return;\n }\n\n this.#tryClearNeedsProfilePairing(epochAtStart);\n\n const profileIdChanged = previousCanonical !== newCanonical;\n const shouldEmitProfileSignInEvent =\n profileIdChanged || profileAliases.length > 0;\n\n if (shouldEmitProfileSignInEvent) {\n this.messenger.publish('AuthenticationController:profileSignIn', {\n profileId: newCanonical,\n profileAliases,\n profileIdChanged,\n });\n }\n }\n\n async #pairSrpProfiles(accessTokens: string[]): Promise<ProfileAlias[]> {\n if (accessTokens.length < 2) {\n return [];\n }\n const primaryAccessToken = accessTokens[0]; // Associated with primary SRP.\n const {\n profileAliases,\n profile: { canonicalProfileId },\n } = await this.#auth.pairSrpProfiles(accessTokens, primaryAccessToken);\n this.#propagateCanonical(canonicalProfileId);\n return profileAliases;\n }\n\n #propagateCanonical(canonicalProfileId: string): void {\n const { srpSessionData } = this.state;\n if (!srpSessionData) {\n return;\n }\n\n this.update((state) => {\n for (const entry of Object.values(state.srpSessionData ?? {})) {\n if (entry?.profile) {\n entry.profile.canonicalProfileId = canonicalProfileId;\n }\n }\n });\n }\n\n /**\n * Returns the canonical profile id from the primary SRP's cached session.\n * Returns `null` when no session exists yet for the primary SRP.\n *\n * Always reads from the primary SRP because the canonical is shared across\n * all paired SRPs after `#propagateCanonical`.\n *\n * @returns The canonical profile id, or `null` if unavailable.\n */\n #getCanonicalProfileId(): string | null {\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n return (\n this.state.srpSessionData?.[primaryEntropySourceId]?.profile\n ?.canonicalProfileId ?? null\n );\n }\n\n public performSignOut(): void {\n this.update((state) => {\n state.isSignedIn = false;\n state.srpSessionData = undefined;\n });\n }\n\n /**\n * Returns a bearer token for the specified SRP, logging in if needed.\n *\n * When called without `entropySourceId`, returns the primary (first) SRP's\n * access token, which is effectively the canonical\n * profile's token that can be used by alias-aware consumers for cross-SRP\n * operations.\n *\n * @param entropySourceId - The entropy source ID. Omit for the primary SRP.\n * @returns The OIDC access token.\n */\n public async getBearerToken(entropySourceId?: string): Promise<string> {\n this.#assertIsUnlocked('getBearerToken');\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n return await this.#auth.getAccessToken(resolvedId);\n }\n\n /**\n * Returns the cached session profile, logging in if no session exists.\n *\n * The returned `canonicalProfileId` reflects the value from the most recent\n * login or pairing. In the rare event where a canonical changed because of\n * a pairing that happened on another device, the cached value may be stale\n * until the next login. For guaranteed freshness, call\n * `refreshCanonicalProfileId()` before reading `canonicalProfileId`.\n *\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns profile for the session.\n */\n public async getSessionProfile(\n entropySourceId?: string,\n ): Promise<UserProfile> {\n this.#assertIsUnlocked('getSessionProfile');\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n return await this.#auth.getUserProfile(resolvedId);\n }\n\n /**\n * Forces a fresh retrieval of the canonical profile ID from the server\n * and propagates it to all cached SRP sessions.\n *\n * This method invalidates the primary SRP's cached session and forces a\n * re-login. Use it before operations that require a guaranteed-fresh\n * canonical (e.g. storage key derivation for Accounts ADR 0005). For\n * best-effort reads, use\n * `getSessionProfile().canonicalProfileId` instead.\n *\n * Only the primary SRP is re-logged-in regardless of how many SRPs exist —\n * the server returns the current canonical for the entire pairing group\n * from any single SRP login.\n *\n * @returns The refreshed canonical profile ID.\n */\n public async refreshCanonicalProfileId(): Promise<string> {\n this.#assertIsUnlocked('refreshCanonicalProfileId');\n\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n this.#invalidateSrpSession(primaryEntropySourceId);\n await this.#auth.getAccessToken(primaryEntropySourceId);\n\n const canonical = this.#getCanonicalProfileId();\n if (!canonical) {\n throw new Error(\n 'refreshCanonicalProfileId - Unable to resolve canonical profile ID',\n );\n }\n\n this.#propagateCanonical(canonical);\n return canonical;\n }\n\n #invalidateSrpSession(entropySourceId: string): void {\n this.update((state) => {\n const entry = state.srpSessionData?.[entropySourceId];\n if (entry?.profile) {\n // Setting canonicalProfileId to '' forces a re-fetch on the next\n // #getAuthSession call. The falsy check (!auth.profile.canonicalProfileId)\n // treats '' the same as undefined/null — all signal an invalid session.\n entry.profile.canonicalProfileId = '';\n }\n });\n }\n\n public async getUserProfileLineage(\n entropySourceId?: string,\n ): Promise<UserProfileLineage> {\n this.#assertIsUnlocked('getUserProfileLineage');\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n return await this.#auth.getUserProfileLineage(resolvedId);\n }\n\n /**\n * Returns a Customer Service specific access token for the specified SRP,\n * logging in if needed.\n *\n * Exchanges the OIDC access token for a short-lived token scoped to the\n * customer-service audience. Customer Service tooling consumes this token to\n * identify and authenticate the user.\n *\n * @param entropySourceId - The entropy source ID. Omit for the primary SRP.\n * @returns The customer-service access token.\n */\n public async getCustomerServiceToken(\n entropySourceId?: string,\n ): Promise<string> {\n this.#assertIsUnlocked('getCustomerServiceToken');\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n return await this.#auth.getCustomerServiceToken(resolvedId);\n }\n\n public isSignedIn(): boolean {\n return this.state.isSignedIn;\n }\n\n /**\n * Reads the BIP-39 seed for an HD entropy source from KeyringController.\n *\n * @param entropySourceId - Entropy source ID. Defaults to the primary HD\n * keyring.\n * @returns The HD keyring seed.\n */\n async #getHdKeyringSeed(entropySourceId?: string): Promise<Uint8Array> {\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n return getHdKeyringSeed(this.messenger, resolvedId);\n }\n\n /**\n * Returns the message-signing public key via native SIP-6 derivation\n * (same key as `@metamask/message-signing-snap` with empty salt).\n *\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns The public key hex.\n */\n async #getPublicKey(entropySourceId?: string): Promise<string> {\n this.#assertIsUnlocked('#getPublicKey');\n const seed = await this.#getHdKeyringSeed(entropySourceId);\n return getMessageSigningPublicKey(seed);\n }\n\n #_signMessageCache: Record<string, string> = {};\n\n /**\n * Builds a cache key scoped to a specific entropy source, so each SRP's\n * signature stays isolated (same pattern as `UserStorageController`).\n *\n * When `entropySourceId` is omitted (primary SRP), it is resolved to the\n * primary HD keyring's metadata ID rather than a stable literal. Because that\n * ID is randomly regenerated whenever the vault is recreated (e.g. on\n * restore), the cached entry is naturally invalidated across vaults — a\n * different SRP can never inherit the previous primary's cached signature.\n *\n * @param message - The tagged message used for signing.\n * @param entropySourceId - The entropy source ID. Omit for the primary SRP.\n * @returns The scoped cache key.\n */\n #scopedCacheKey(\n message: `metamask:${string}`,\n entropySourceId?: string,\n ): string {\n return `${entropySourceId ?? this.#getPrimaryEntropySourceId()}:${message}`;\n }\n\n /**\n * Signs a `metamask:…` message with the native SIP-6 message-signing key.\n *\n * @param message - A specific tagged message to sign.\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns Compact secp256k1 signature hex.\n */\n async #signMessage(\n message: string,\n entropySourceId?: string,\n ): Promise<string> {\n assertMessageStartsWithMetamask(message);\n this.#assertIsUnlocked('#signMessage');\n\n const cacheKey = this.#scopedCacheKey(message, entropySourceId);\n if (this.#_signMessageCache[cacheKey]) {\n return this.#_signMessageCache[cacheKey];\n }\n\n const seed = await this.#getHdKeyringSeed(entropySourceId);\n const result = await signMessageWithMessageSigningKey(message, seed);\n\n this.#_signMessageCache[cacheKey] = result;\n\n return result;\n }\n}\n"]}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { BaseController } from "@metamask/base-controller";
|
|
2
2
|
import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
|
|
3
|
-
import type { KeyringControllerGetStateAction, KeyringControllerLockEvent, KeyringControllerUnlockEvent } from "@metamask/keyring-controller";
|
|
3
|
+
import type { KeyringControllerGetStateAction, KeyringControllerLockEvent, KeyringControllerUnlockEvent, KeyringControllerWithKeyringV2UnsafeAction } from "@metamask/keyring-controller";
|
|
4
4
|
import type { Messenger } from "@metamask/messenger";
|
|
5
5
|
import type { SeedlessOnboardingControllerGetStateAction } from "@metamask/seedless-onboarding-controller";
|
|
6
|
-
import type { SnapControllerHandleRequestAction } from "@metamask/snaps-controllers";
|
|
7
6
|
import type { LoginResponse, ProfileAlias, UserProfile, UserProfileLineage } from "../../sdk/index.cjs";
|
|
8
7
|
import { Env } from "../../sdk/index.cjs";
|
|
9
8
|
import type { MetaMetricsAuth } from "../../shared/types/services.cjs";
|
|
@@ -42,7 +41,7 @@ export type AuthenticationControllerProfileSignInEvent = {
|
|
|
42
41
|
payload: [ProfileSignInInfo];
|
|
43
42
|
};
|
|
44
43
|
export type Events = AuthenticationControllerStateChangeEvent | AuthenticationControllerProfileSignInEvent;
|
|
45
|
-
type AllowedActions = KeyringControllerGetStateAction |
|
|
44
|
+
type AllowedActions = KeyringControllerGetStateAction | KeyringControllerWithKeyringV2UnsafeAction | SeedlessOnboardingControllerGetStateAction;
|
|
46
45
|
type AllowedEvents = KeyringControllerLockEvent | KeyringControllerUnlockEvent;
|
|
47
46
|
export type AuthenticationControllerMessenger = Messenger<typeof controllerName, Actions | AllowedActions, Events | AllowedEvents>;
|
|
48
47
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthenticationController.d.cts","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,KAAK,EACV,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,
|
|
1
|
+
{"version":3,"file":"AuthenticationController.d.cts","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,KAAK,EACV,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAC5B,0CAA0C,EAC3C,qCAAqC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,0CAA0C,EAAE,iDAAiD;AAG3G,OAAO,KAAK,EAEV,aAAa,EACb,YAAY,EAGZ,WAAW,EACX,kBAAkB,EACnB,4BAA2B;AAC5B,OAAO,EAGL,GAAG,EAEJ,4BAA2B;AAC5B,OAAO,KAA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,aAAa,CACvB,CAAC;AAEF;;;GAGG;AACH,qBAAa,wBAAyB,SAAQ,cAAc,CAC1D,OAAO,cAAc,EACrB,6BAA6B,EAC7B,iCAAiC,CAClC;;gBA+Ba,EACV,SAAS,EACT,KAAK,EACL,MAAM,EACN,WAAW,GACZ,EAAE;QACD,SAAS,EAAE,iCAAiC,CAAC;QAC7C,KAAK,CAAC,EAAE,6BAA6B,CAAC;QACtC,MAAM,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,CAAC;QACnC;;;WAGG;QACH,WAAW,EAAE,eAAe,CAAC;KAC9B;IAiMY,aAAa,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IA6B/C;;;;OAIG;IACI,qBAAqB,IAAI,IAAI;IA8G7B,cAAc,IAAI,IAAI;IAO7B;;;;;;;;;;OAUG;IACU,cAAc,CAAC,eAAe,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAMtE;;;;;;;;;;;;OAYG;IACU,iBAAiB,CAC5B,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,WAAW,CAAC;IAMvB;;;;;;;;;;;;;;;OAeG;IACU,yBAAyB,IAAI,OAAO,CAAC,MAAM,CAAC;IA8B5C,qBAAqB,CAChC,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,kBAAkB,CAAC;IAM9B;;;;;;;;;;OAUG;IACU,uBAAuB,CAClC,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,CAAC;IAMX,UAAU,IAAI,OAAO;CAgF7B"}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { BaseController } from "@metamask/base-controller";
|
|
2
2
|
import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
|
|
3
|
-
import type { KeyringControllerGetStateAction, KeyringControllerLockEvent, KeyringControllerUnlockEvent } from "@metamask/keyring-controller";
|
|
3
|
+
import type { KeyringControllerGetStateAction, KeyringControllerLockEvent, KeyringControllerUnlockEvent, KeyringControllerWithKeyringV2UnsafeAction } from "@metamask/keyring-controller";
|
|
4
4
|
import type { Messenger } from "@metamask/messenger";
|
|
5
5
|
import type { SeedlessOnboardingControllerGetStateAction } from "@metamask/seedless-onboarding-controller";
|
|
6
|
-
import type { SnapControllerHandleRequestAction } from "@metamask/snaps-controllers";
|
|
7
6
|
import type { LoginResponse, ProfileAlias, UserProfile, UserProfileLineage } from "../../sdk/index.mjs";
|
|
8
7
|
import { Env } from "../../sdk/index.mjs";
|
|
9
8
|
import type { MetaMetricsAuth } from "../../shared/types/services.mjs";
|
|
@@ -42,7 +41,7 @@ export type AuthenticationControllerProfileSignInEvent = {
|
|
|
42
41
|
payload: [ProfileSignInInfo];
|
|
43
42
|
};
|
|
44
43
|
export type Events = AuthenticationControllerStateChangeEvent | AuthenticationControllerProfileSignInEvent;
|
|
45
|
-
type AllowedActions = KeyringControllerGetStateAction |
|
|
44
|
+
type AllowedActions = KeyringControllerGetStateAction | KeyringControllerWithKeyringV2UnsafeAction | SeedlessOnboardingControllerGetStateAction;
|
|
46
45
|
type AllowedEvents = KeyringControllerLockEvent | KeyringControllerUnlockEvent;
|
|
47
46
|
export type AuthenticationControllerMessenger = Messenger<typeof controllerName, Actions | AllowedActions, Events | AllowedEvents>;
|
|
48
47
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthenticationController.d.mts","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,KAAK,EACV,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,
|
|
1
|
+
{"version":3,"file":"AuthenticationController.d.mts","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3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;;;;OAUG;IACU,uBAAuB,CAClC,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,CAAC;IAMX,UAAU,IAAI,OAAO;CAgF7B"}
|
|
@@ -9,11 +9,12 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
|
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
10
10
|
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
11
11
|
};
|
|
12
|
-
var _AuthenticationController_instances, _AuthenticationController_metametrics, _AuthenticationController_auth, _AuthenticationController_config, _AuthenticationController_isUnlocked, _AuthenticationController_profilePairingRequestEpoch, _AuthenticationController_keyringController, _AuthenticationController_getLoginResponseFromState, _AuthenticationController_setLoginResponseToState, _AuthenticationController_assertIsUnlocked, _AuthenticationController_getHdKeyringEntropySourceIds, _AuthenticationController_getPrimaryEntropySourceId, _AuthenticationController_getLoginTag, _AuthenticationController_getLoginIdentifierType, _AuthenticationController_resolveSocialIdentifierType, _AuthenticationController_tryClearNeedsProfilePairing, _AuthenticationController_doPair, _AuthenticationController_pairSrpProfiles, _AuthenticationController_propagateCanonical, _AuthenticationController_getCanonicalProfileId, _AuthenticationController_invalidateSrpSession,
|
|
12
|
+
var _AuthenticationController_instances, _AuthenticationController_metametrics, _AuthenticationController_auth, _AuthenticationController_config, _AuthenticationController_isUnlocked, _AuthenticationController_profilePairingRequestEpoch, _AuthenticationController_keyringController, _AuthenticationController_getLoginResponseFromState, _AuthenticationController_setLoginResponseToState, _AuthenticationController_assertIsUnlocked, _AuthenticationController_getHdKeyringEntropySourceIds, _AuthenticationController_getPrimaryEntropySourceId, _AuthenticationController_getLoginTag, _AuthenticationController_getLoginIdentifierType, _AuthenticationController_resolveSocialIdentifierType, _AuthenticationController_tryClearNeedsProfilePairing, _AuthenticationController_doPair, _AuthenticationController_pairSrpProfiles, _AuthenticationController_propagateCanonical, _AuthenticationController_getCanonicalProfileId, _AuthenticationController_invalidateSrpSession, _AuthenticationController_getHdKeyringSeed, _AuthenticationController_getPublicKey, _AuthenticationController__signMessageCache, _AuthenticationController_scopedCacheKey, _AuthenticationController_signMessage;
|
|
13
13
|
import { BaseController } from "@metamask/base-controller";
|
|
14
14
|
import { assertMessageStartsWithMetamask, AuthType, Env, JwtBearerAuth } from "../../sdk/index.mjs";
|
|
15
15
|
import { getHdKeyringEntropySourceIds, getPrimaryHdKeyringEntropySourceId } from "../../shared/utils/entropy-source.mjs";
|
|
16
|
-
import {
|
|
16
|
+
import { getHdKeyringSeed } from "../../shared/utils/hd-keyring-seed.mjs";
|
|
17
|
+
import { getMessageSigningPublicKey, signMessageWithMessageSigningKey } from "../../shared/utils/message-signing.mjs";
|
|
17
18
|
const controllerName = 'AuthenticationController';
|
|
18
19
|
export const defaultState = {
|
|
19
20
|
isSignedIn: false,
|
|
@@ -103,7 +104,7 @@ export class AuthenticationController extends BaseController {
|
|
|
103
104
|
});
|
|
104
105
|
},
|
|
105
106
|
});
|
|
106
|
-
|
|
107
|
+
_AuthenticationController__signMessageCache.set(this, {});
|
|
107
108
|
if (!metametrics) {
|
|
108
109
|
throw new Error('`metametrics` field is required');
|
|
109
110
|
}
|
|
@@ -122,8 +123,8 @@ export class AuthenticationController extends BaseController {
|
|
|
122
123
|
setLoginResponse: __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_setLoginResponseToState).bind(this),
|
|
123
124
|
},
|
|
124
125
|
signing: {
|
|
125
|
-
getIdentifier: __classPrivateFieldGet(this, _AuthenticationController_instances, "m",
|
|
126
|
-
signMessage: __classPrivateFieldGet(this, _AuthenticationController_instances, "m",
|
|
126
|
+
getIdentifier: __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getPublicKey).bind(this),
|
|
127
|
+
signMessage: __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_signMessage).bind(this),
|
|
127
128
|
},
|
|
128
129
|
getLoginTag: __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getLoginTag).bind(this),
|
|
129
130
|
getLoginIdentifierType: __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getLoginIdentifierType).bind(this),
|
|
@@ -264,7 +265,7 @@ export class AuthenticationController extends BaseController {
|
|
|
264
265
|
return this.state.isSignedIn;
|
|
265
266
|
}
|
|
266
267
|
}
|
|
267
|
-
_AuthenticationController_metametrics = new WeakMap(), _AuthenticationController_auth = new WeakMap(), _AuthenticationController_config = new WeakMap(), _AuthenticationController_isUnlocked = new WeakMap(), _AuthenticationController_profilePairingRequestEpoch = new WeakMap(), _AuthenticationController_keyringController = new WeakMap(),
|
|
268
|
+
_AuthenticationController_metametrics = new WeakMap(), _AuthenticationController_auth = new WeakMap(), _AuthenticationController_config = new WeakMap(), _AuthenticationController_isUnlocked = new WeakMap(), _AuthenticationController_profilePairingRequestEpoch = new WeakMap(), _AuthenticationController_keyringController = new WeakMap(), _AuthenticationController__signMessageCache = new WeakMap(), _AuthenticationController_instances = new WeakSet(), _AuthenticationController_getLoginResponseFromState = async function _AuthenticationController_getLoginResponseFromState(entropySourceId) {
|
|
268
269
|
const resolvedId = entropySourceId ?? __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getPrimaryEntropySourceId).call(this);
|
|
269
270
|
if (!this.state.srpSessionData?.[resolvedId]) {
|
|
270
271
|
return null;
|
|
@@ -434,35 +435,51 @@ async function _AuthenticationController_doPair(accessTokens, epochAtStart) {
|
|
|
434
435
|
entry.profile.canonicalProfileId = '';
|
|
435
436
|
}
|
|
436
437
|
});
|
|
437
|
-
},
|
|
438
|
+
}, _AuthenticationController_getHdKeyringSeed =
|
|
438
439
|
/**
|
|
439
|
-
*
|
|
440
|
+
* Reads the BIP-39 seed for an HD entropy source from KeyringController.
|
|
441
|
+
*
|
|
442
|
+
* @param entropySourceId - Entropy source ID. Defaults to the primary HD
|
|
443
|
+
* keyring.
|
|
444
|
+
* @returns The HD keyring seed.
|
|
445
|
+
*/
|
|
446
|
+
async function _AuthenticationController_getHdKeyringSeed(entropySourceId) {
|
|
447
|
+
const resolvedId = entropySourceId ?? __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getPrimaryEntropySourceId).call(this);
|
|
448
|
+
return getHdKeyringSeed(this.messenger, resolvedId);
|
|
449
|
+
}, _AuthenticationController_getPublicKey =
|
|
450
|
+
/**
|
|
451
|
+
* Returns the message-signing public key via native SIP-6 derivation
|
|
452
|
+
* (same key as `@metamask/message-signing-snap` with empty salt).
|
|
440
453
|
*
|
|
441
454
|
* @param entropySourceId - The entropy source ID used to derive the key,
|
|
442
455
|
* when multiple sources are available (Multi-SRP).
|
|
443
|
-
* @returns The
|
|
456
|
+
* @returns The public key hex.
|
|
444
457
|
*/
|
|
445
|
-
async function
|
|
446
|
-
__classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#
|
|
447
|
-
const
|
|
448
|
-
return
|
|
449
|
-
},
|
|
458
|
+
async function _AuthenticationController_getPublicKey(entropySourceId) {
|
|
459
|
+
__classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#getPublicKey');
|
|
460
|
+
const seed = await __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getHdKeyringSeed).call(this, entropySourceId);
|
|
461
|
+
return getMessageSigningPublicKey(seed);
|
|
462
|
+
}, _AuthenticationController_scopedCacheKey = function _AuthenticationController_scopedCacheKey(message, entropySourceId) {
|
|
463
|
+
return `${entropySourceId ?? __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getPrimaryEntropySourceId).call(this)}:${message}`;
|
|
464
|
+
}, _AuthenticationController_signMessage =
|
|
450
465
|
/**
|
|
451
|
-
* Signs a
|
|
466
|
+
* Signs a `metamask:…` message with the native SIP-6 message-signing key.
|
|
452
467
|
*
|
|
453
468
|
* @param message - A specific tagged message to sign.
|
|
454
469
|
* @param entropySourceId - The entropy source ID used to derive the key,
|
|
455
470
|
* when multiple sources are available (Multi-SRP).
|
|
456
|
-
* @returns
|
|
471
|
+
* @returns Compact secp256k1 signature hex.
|
|
457
472
|
*/
|
|
458
|
-
async function
|
|
473
|
+
async function _AuthenticationController_signMessage(message, entropySourceId) {
|
|
459
474
|
assertMessageStartsWithMetamask(message);
|
|
460
|
-
|
|
461
|
-
|
|
475
|
+
__classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#signMessage');
|
|
476
|
+
const cacheKey = __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_scopedCacheKey).call(this, message, entropySourceId);
|
|
477
|
+
if (__classPrivateFieldGet(this, _AuthenticationController__signMessageCache, "f")[cacheKey]) {
|
|
478
|
+
return __classPrivateFieldGet(this, _AuthenticationController__signMessageCache, "f")[cacheKey];
|
|
462
479
|
}
|
|
463
|
-
__classPrivateFieldGet(this, _AuthenticationController_instances, "m",
|
|
464
|
-
const result =
|
|
465
|
-
__classPrivateFieldGet(this,
|
|
480
|
+
const seed = await __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_getHdKeyringSeed).call(this, entropySourceId);
|
|
481
|
+
const result = await signMessageWithMessageSigningKey(message, seed);
|
|
482
|
+
__classPrivateFieldGet(this, _AuthenticationController__signMessageCache, "f")[cacheKey] = result;
|
|
466
483
|
return result;
|
|
467
484
|
};
|
|
468
485
|
//# sourceMappingURL=AuthenticationController.mjs.map
|