@metamask-previews/profile-sync-controller 33.0.0-preview-0f8c056e2 → 33.0.0-preview-c2be02bd4

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
@@ -9,10 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ### Changed
11
11
 
12
+ - Replace JS AES implementation with `@metamask/cryptography` ([#10621](https://github.com/MetaMask/core/pull/10621))
12
13
  - Bump `immer` from `^9.0.21` to `^11.1.18` ([#10382](https://github.com/MetaMask/core/pull/10382))
13
14
 
14
15
  ### Fixed
15
16
 
17
+ - Coalesce overlapping `performSignIn` calls so only one sign-in runs at a time ([#10646](https://github.com/MetaMask/core/pull/10646))
16
18
  - Rely on `@metamask/key-tree` crypto implementation for HMAC-SHA-512 instead of hardcoded `noble` implementation ([#10424](https://github.com/MetaMask/core/pull/10424))
17
19
  - `@metamask/key-tree` uses WebCrypto API if available and fallback to `noble` otherwise.
18
20
  - One note, we expect the platform to provide a fully-compliant WebCrypto (`crypto.subtle`) implementation for this to work (`@metamask/key-tree` detection is global and not "per crypto functions").
@@ -1 +1 @@
1
- {"version":3,"file":"AuthenticationController.d.ts","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,aAAa,EAAgB,MAAM,4BAA4B,CAAC;AAE9E,OAAO,KAAK,EACV,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAC5B,0CAA0C,EAC3C,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EACV,gDAAgD,EAChD,0CAA0C,E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BAAiB,EAC3B,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,CAAC,CAQjB;IAEM,UAAU,IAAI,OAAO,CAE3B;CA8EF"}
1
+ {"version":3,"file":"AuthenticationController.d.ts","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,aAAa,EAAgB,MAAM,4BAA4B,CAAC;AAE9E,OAAO,KAAK,EACV,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAC5B,0CAA0C,EAC3C,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EACV,gDAAgD,EAChD,0CAA0C,EAC3C,MAAM,0CAA0C,CAAC;AAYlD,OAAO,KAAK,EAEV,aAAa,EACb,YAAY,EAIZ,WAAW,EACX,kBAAkB,EAClB,iBAAiB,EACjB,eAAe,EACf,sBAAsB,EACtB,yBAAyB,EACzB,kBAAkB,EAClB,mBAAmB,EACnB,wBAAwB,EACxB,2BAA2B,EAC3B,iBAAiB,EACjB,2BAA2B,EAC3B,qBAAqB,EACtB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAGL,GAAG,EAKJ,MAAM,oBAAoB,CAAC;AAG5B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAOtE,OAAO,EAAE,qCAAqC,EAAE,MAAM,mDAAmD,CAAC;AAE1G,QAAA,MAAM,cAAc,6BAA6B,CAAC;AAGlD,MAAM,MAAM,6BAA6B,GAAG;IAC1C,UAAU,EAAE,OAAO,CAAC;IACpB,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAC/C;;;;OAIG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5B;IAED;;;OAGG;IACI,UAAU,IAAI,IAAI,CAMxB;IAED;;;;;;;;;;OAUG;IACU,cAAc,CAAC,eAAe,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAIrE;IAED;;;;;;;;;;;;OAYG;IACU,iBAAiB,CAC5B,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,WAAW,CAAC,CAItB;IAED;;;;;;;;;;;;;;;OAeG;IACU,yBAAyB,IAAI,OAAO,CAAC,MAAM,CAAC,CAgBxD;IAcY,qBAAqB,CAChC,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,kBAAkB,CAAC,CAI7B;IAED;;;;;;;;;;OAUG;IACU,uBAAuB,CAClC,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,CAAC,CAIjB;IAED;;;;;;;;;;;;OAYG;IACU,uBAAuB,CAClC,MAAM,EAAE,eAAe,EACvB,QAAQ,EAAE,iBAAiB,EAC3B,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,CAAC,CAQjB;IAEM,UAAU,IAAI,OAAO,CAE3B;CA8EF"}
@@ -147,6 +147,10 @@ export class AuthenticationController extends BaseController {
147
147
  * `performSignIn` can't clear `needsProfilePairing` afterwards.
148
148
  */
149
149
  #profilePairingRequestEpoch = 0;
150
+ /**
151
+ * Sign-in currently running. Overlapping callers share it.
152
+ */
153
+ #ongoingSignIn;
150
154
  #keyringController = {
151
155
  setupLockedStateSubscriptions: () => {
152
156
  const { isUnlocked } = this.messenger.call('KeyringController:getState');
@@ -349,6 +353,18 @@ export class AuthenticationController extends BaseController {
349
353
  }
350
354
  async performSignIn() {
351
355
  this.#assertIsUnlocked('performSignIn');
356
+ if (this.#ongoingSignIn) {
357
+ return await this.#ongoingSignIn;
358
+ }
359
+ const signIn = this.#runPerformSignIn().finally(() => {
360
+ if (this.#ongoingSignIn === signIn) {
361
+ this.#ongoingSignIn = undefined;
362
+ }
363
+ });
364
+ this.#ongoingSignIn = signIn;
365
+ return await signIn;
366
+ }
367
+ async #runPerformSignIn() {
352
368
  const epochAtStart = this.#profilePairingRequestEpoch;
353
369
  const entropySourceIds = this.#getHdKeyringEntropySourceIds();
354
370
  const accessTokens = [];
@@ -1 +1 @@
1
- {"version":3,"file":"AuthenticationController.js","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAO3D,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAc/E,OAAO,EACL,4BAA4B,EAC5B,+BAA+B,EAC/B,qBAAqB,EACrB,8BAA8B,EAC9B,iCAAiC,EACjC,iCAAiC,EACjC,4BAA4B,GAC7B,MAAM,oDAAoD,CAAC;AAsB5D,OAAO,EACL,+BAA+B,EAC/B,QAAQ,EACR,GAAG,EACH,aAAa,EACb,iBAAiB,EACjB,eAAe,EACf,6BAA6B,GAC9B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAC;AAErE,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AACzE,OAAO,EACL,0BAA0B,EAC1B,gCAAgC,GACjC,MAAM,uCAAuC,CAAC;AAG/C,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAsClD,MAAM,CAAC,MAAM,YAAY,GAAkC;IACzD,UAAU,EAAE,KAAK;IACjB,mBAAmB,EAAE,EAAE;IACvB,mBAAmB,EAAE,IAAI;IACzB,kBAAkB,EAAE,IAAI;CACzB,CAAC;AACF,MAAM,QAAQ,GAAiD;IAC7D,UAAU,EAAE;QACV,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI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,IAAI,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAAC;QAC3D,OAAO,0BAA0B,CAAC,IAAI,CAAC,CAAC;IAC1C,CAAC;IAED,kBAAkB,GAA2B,EAAE,CAAC;IAEhD;;;;;;;;;;;;;OAaG;IACH,eAAe,CACb,OAA6B,EAC7B,eAAwB;QAExB,OAAO,GAAG,eAAe,IAAI,IAAI,CAAC,0BAA0B,EAAE,IAAI,OAAO,EAAE,CAAC;IAC9E,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,YAAY,CAChB,OAAe,EACf,eAAwB;QAExB,+BAA+B,CAAC,OAAO,CAAC,CAAC;QACzC,IAAI,CAAC,iBAAiB,CAAC,cAAc,CAAC,CAAC;QAEvC,MAAM,QAAQ,GAAG,IAAI,CAAC,eAAe,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;QAChE,IAAI,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,EAAE,CAAC;YACtC,OAAO,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,CAAC;QAC3C,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAAC;QAC3D,MAAM,MAAM,GAAG,MAAM,gCAAgC,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QAErE,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC;QAE3C,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type { TraceCallback, TraceContext } from '@metamask/controller-utils';\nimport { selectHdKeyringEntropySourceIds } from '@metamask/keyring-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n KeyringControllerWithKeyringV2UnsafeAction,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\n SeedlessOnboardingControllerGetAccessTokenAction,\n SeedlessOnboardingControllerGetStateAction,\n} from '@metamask/seedless-onboarding-controller';\nimport type { Json } from '@metamask/utils';\n\nimport {\n BeginEnrollmentRequestStruct,\n CompleteEnrollmentRequestStruct,\n assertValidMfaRequest,\n BeginVerificationRequestStruct,\n CompleteVerificationRequestStruct,\n GetVerificationTokenRequestStruct,\n parseVerificationTokenClaims,\n} from '../../sdk/authentication-jwt-bearer/mfa/schemas.js';\nimport type {\n LoginIdentifierType,\n LoginResponse,\n ProfileAlias,\n ProfileIdentifier,\n SRPInterface,\n SrpLoginTag,\n UserProfile,\n UserProfileLineage,\n OidcTokenAudience,\n OidcTokenClaims,\n BeginEnrollmentRequest,\n CompleteEnrollmentRequest,\n EnrolledCredential,\n EnrollmentChallenge,\n BeginVerificationRequest,\n CompleteVerificationRequest,\n VerificationToken,\n GetVerificationTokenRequest,\n VerificationChallenge,\n} from '../../sdk/index.js';\nimport {\n assertMessageStartsWithMetamask,\n AuthType,\n Env,\n JwtBearerAuth,\n PairConflictError,\n getMfaErrorCode,\n VerificationTokenInvalidError,\n} from '../../sdk/index.js';\nimport { decodeJwtPayload } from '../../sdk/utils/jwt.js';\nimport { toErrorMessage } from '../../sdk/utils/to-error-message.js';\nimport type { MetaMetricsAuth } from '../../shared/types/services.js';\nimport { getPrimaryHdKeyringEntropySourceId } 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 * Credentials fetched for the current profile. The controller always seeds\n * this to an empty array; it remains optional so partial-state selectors stay\n * assignable to the controller state type.\n */\n enrolledCredentials?: EnrolledCredential[];\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 /**\n * Client gate for social identifier pairing. Defaults to `true` (fresh\n * install / upgrade), set to `false` after a successful or 409\n * `POST /api/v2/profile/pair/identifier`, left `true` on other failures\n * so the next `performSignIn` retries, and cleared without an API call\n * when the user never logged in with a social provider.\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 needsSocialPairing?: boolean;\n};\nexport const defaultState: AuthenticationControllerState = {\n isSignedIn: false,\n enrolledCredentials: [],\n needsProfilePairing: true,\n needsSocialPairing: 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 needsSocialPairing: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n srpSessionData: {\n // Remove access token and paired identifiers 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 const {\n pairedIdentifierIds: _unusedPairedIdentifierIds,\n ...profileWithoutPairedIdentifierIds\n } = value.profile;\n sanitizedSrpSessionData[key] = {\n ...value,\n token: tokenWithoutAccessToken,\n profile: profileWithoutPairedIdentifierIds,\n };\n return sanitizedSrpSessionData;\n },\n {},\n );\n },\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n enrolledCredentials: {\n // Allow-list so new credential types cannot leak identifiers by default.\n includeInStateLogs: (credentials) =>\n credentials?.map(({ type, status, enrolledAt }) => ({\n type,\n status,\n ...(enrolledAt === undefined ? {} : { enrolledAt }),\n })) ?? null,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\n/**\n * Upper bound on a verification session's lifetime. The session also ends at\n * the verification token's own `exp` (15 minutes today), whichever comes\n * first, so this only matters if the server ever issues longer-lived tokens.\n * Callers needing a fresher proof pass `maxSessionAgeMs` to\n * `getVerificationToken`.\n */\nexport const VERIFICATION_SESSION_TTL_MS = 15 * 60_000;\n\n/**\n * Default maximum age of a verification session that may authorize enrolling a\n * credential. A session opened for an unrelated operation must not be able to\n * add a factor long after the fact, while a session proven moments ago (or\n * during the same setup flow, via `maxSessionAgeMs`) may.\n */\nexport const ENROLLMENT_MAX_SESSION_AGE_MS = 2 * 60_000;\n\n/**\n * Key of the only verification session held today. Sessions are keyed by token\n * audience so audience-scoped tokens can be added without reshaping storage.\n */\nconst DEFAULT_AUDIENCE = '';\n\ntype VerificationSession = {\n token: VerificationToken;\n expiresAt: number;\n timer: ReturnType<typeof setTimeout>;\n};\ntype ControllerConfig = {\n env: Env;\n /**\n * When `true`, `performSignIn` attempts to attach the Google/Apple/\n * Telegram social identifier to the primary SRP profile. Defaults to\n * `() => false`.\n */\n isSocialPairingEnabled: () => boolean;\n};\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'performSignIn',\n 'performSignOut',\n 'getBearerToken',\n 'getSessionProfile',\n 'refreshCanonicalProfileId',\n 'getUserProfileLineage',\n 'getCustomerServiceToken',\n 'getPartnerIdentityToken',\n 'isSignedIn',\n 'requestProfilePairing',\n 'clearState',\n 'refreshEnrolledCredentials',\n 'beginCredentialEnrollment',\n 'completeCredentialEnrollment',\n 'beginCredentialVerification',\n 'completeCredentialVerification',\n 'getVerificationToken',\n 'clearVerificationSession',\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 | SeedlessOnboardingControllerGetAccessTokenAction;\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 #trace: TraceCallback;\n\n readonly #config: ControllerConfig = {\n env: Env.PRD,\n isSocialPairingEnabled: () => false,\n };\n\n #isUnlocked = false;\n\n /**\n * Bumped whenever the authenticated session ends, so an in-flight MFA\n * ceremony started under the previous session cannot apply its result.\n */\n #authSessionEpoch = 0;\n\n /**\n * Verification sessions keyed by token audience. At most one session per\n * audience; only `DEFAULT_AUDIENCE` is used until audience-scoped tokens\n * exist.\n */\n readonly #verificationSessions = new Map<string, VerificationSession>();\n\n /**\n * Sequence number of the most recently started credentials refresh. Only\n * that refresh may write the cache, so a slower, earlier request cannot\n * overwrite a newer list (e.g. an explicit refresh landing after an\n * enrollment's refresh).\n */\n #credentialsRefreshSeq = 0;\n\n /**\n * Bumped by `requestProfilePairing` and `clearState` so an in-flight\n * `performSignIn` can't clear `needsProfilePairing` afterwards.\n */\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.#authSessionEpoch += 1;\n this.#isUnlocked = false;\n this.clearVerificationSession();\n });\n },\n };\n\n constructor({\n messenger,\n state,\n config,\n metametrics,\n trace,\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 trace?: TraceCallback;\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 // `??` per key so an explicit `undefined` keeps the default rather than\n // clobbering it.\n this.#config = {\n env: config?.env ?? this.#config.env,\n isSocialPairingEnabled:\n config?.isSocialPairingEnabled ?? this.#config.isSocialPairingEnabled,\n };\n\n this.#metametrics = metametrics;\n this.#trace = trace ?? (((_request, fn) => fn?.()) as TraceCallback);\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 // The API omits `paired_identifier_ids` when it fails to load them, so\n // keep the last known value rather than wiping it.\n const pairedIdentifierIds =\n loginResponse.profile.pairedIdentifierIds ??\n state.srpSessionData[resolvedId]?.profile.pairedIdentifierIds;\n state.srpSessionData[resolvedId] = {\n ...loginResponse,\n profile: {\n ...loginResponse.profile,\n metaMetricsId,\n ...(pairedIdentifierIds ? { pairedIdentifierIds } : {}),\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 #assertAuthSessionEpoch(epoch: number, methodName: string): void {\n if (!this.#isUnlocked || this.#authSessionEpoch !== epoch) {\n throw new Error(\n `${methodName} - unable to proceed, the authenticated session ended`,\n );\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 keyringState = this.messenger.call('KeyringController:getState');\n return selectHdKeyringEntropySourceIds(keyringState);\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 keyringState = this.messenger.call('KeyringController:getState');\n return getPrimaryHdKeyringEntropySourceId(keyringState);\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 return this.#identifierTypeFromSeedlessState(\n this.messenger.call('SeedlessOnboardingController:getState'),\n );\n } catch {\n return 'SRP';\n }\n }\n\n /**\n * Maps SeedlessOnboarding vault + `authConnection` to a login identifier\n * type. Does not catch messenger errors — callers decide whether a\n * missing controller is `SRP` or a retryable failure.\n *\n * @param state - SeedlessOnboarding slice used for the mapping.\n * @param state.vault - Encrypted social vault, if present.\n * @param state.authConnection - Social provider id (`google` / `apple` /\n * `telegram`).\n * @returns The social provider identifier type, or `SRP`.\n */\n #identifierTypeFromSeedlessState(state: {\n vault?: string | null;\n authConnection?: string;\n }): LoginIdentifierType {\n if (state.vault === null || state.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 (state.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 }\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 try {\n await this.#trySocialPairing(accessTokens[0]);\n } catch {\n // noop\n }\n\n return accessTokens;\n }\n\n /**\n * Attaches a Google/Apple/Telegram social identifier to the primary SRP\n * profile via `POST /api/v2/profile/pair/identifier`.\n *\n * Runs only when `isSocialPairingEnabled()` is true and\n * `needsSocialPairing` is not `false` (`undefined` is treated as true).\n * No social provider (`authConnection` unset) → clear the flag (nothing\n * to pair). Social provider set but vault missing → skip (onboarding\n * still in flight). Google without email → skip (API requires it).\n * Telegram never sends `email` (the field holds a display name, not an\n * address). Missing social JWT → skip. 409 Conflict → clear the flag\n * (identifier already owned; retry is pointless). Other errors\n * propagate so the caller can swallow them and leave the flag set for\n * retry.\n *\n * @param primaryAccessToken - Primary SRP OIDC access token used as the\n * Bearer credential. The profile associated with this JWT becomes the\n * canonical owner of the social identifier.\n */\n async #trySocialPairing(primaryAccessToken?: string): Promise<void> {\n if (\n !this.#config.isSocialPairingEnabled() ||\n this.state.needsSocialPairing === false ||\n !primaryAccessToken\n ) {\n return;\n }\n\n let seedlessState: {\n vault?: string | null;\n authConnection?: string;\n socialLoginEmail?: string;\n };\n try {\n seedlessState = this.messenger.call(\n 'SeedlessOnboardingController:getState',\n );\n } catch {\n // Controller missing or getState failed — retry next performSignIn.\n return;\n }\n\n // `SRP` here does not describe the vault: it is the mapping's \"no social\n // identity\" result, returned when there is no seedless vault or the\n // provider is unrecognised. In both cases there is nothing to pair.\n const identifierType = this.#identifierTypeFromSeedlessState(seedlessState);\n if (identifierType === 'SRP') {\n const { vault, authConnection } = seedlessState;\n // Vault not written yet but a social provider is already known —\n // onboarding is still in flight. Do not clear; retry next sign-in.\n if ((vault === null || vault === undefined) && Boolean(authConnection)) {\n return;\n }\n this.#clearNeedsSocialPairing();\n return;\n }\n\n // Email policy follows the API contract: GOOGLE requires `email` (400\n // without it), APPLE accepts it optionally, TELEGRAM must not send it\n // (clients store a display name in `socialLoginEmail` for Telegram).\n // Clients request the `email` scope for Google, so a missing value is a\n // defensive case rather than an expected one; returning here leaves\n // `needsSocialPairing` set so the next sign-in retries instead of\n // sending a request that would fail.\n const { socialLoginEmail } = seedlessState;\n let email: string | undefined;\n if (identifierType === 'GOOGLE') {\n if (!socialLoginEmail) {\n return;\n }\n email = socialLoginEmail;\n } else if (identifierType === 'APPLE') {\n email = socialLoginEmail;\n }\n\n const socialJwt = await this.messenger.call(\n 'SeedlessOnboardingController:getAccessToken',\n );\n if (socialJwt === undefined || socialJwt === '') {\n return;\n }\n\n try {\n const pairedIdentifierIds = await this.#auth.pairSocialIdentifier(\n {\n identifierType,\n socialJwt,\n ...(email ? { email } : {}),\n },\n primaryAccessToken,\n );\n this.#setPrimaryPairedIdentifierIds(pairedIdentifierIds);\n this.#clearNeedsSocialPairing();\n } catch (error) {\n if (error instanceof PairConflictError) {\n this.#clearNeedsSocialPairing();\n return;\n }\n throw error;\n }\n }\n\n #clearNeedsSocialPairing(): void {\n if (this.state.needsSocialPairing !== false) {\n this.update((state) => {\n state.needsSocialPairing = false;\n });\n }\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, pairedIdentifierIds },\n } = await this.#auth.pairSrpProfiles(accessTokens, primaryAccessToken);\n this.#propagateCanonical(canonicalProfileId);\n this.#setPrimaryPairedIdentifierIds(pairedIdentifierIds);\n return profileAliases;\n }\n\n /**\n * Pair calls use the primary SRP's token, so their response only describes\n * the primary's profile: secondaries skipped by the server are not in it.\n *\n * @param pairedIdentifierIds - Identifiers returned by the pair call, if any.\n */\n #setPrimaryPairedIdentifierIds(\n pairedIdentifierIds: ProfileIdentifier[] | undefined,\n ): void {\n if (!pairedIdentifierIds) {\n return;\n }\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n this.update((state) => {\n const entry = state.srpSessionData?.[primaryEntropySourceId];\n if (entry?.profile) {\n entry.profile.pairedIdentifierIds = pairedIdentifierIds;\n }\n });\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 /**\n * Runs one MFA network step inside a trace span tagged with the caller's\n * operation and the credential type, recording the outcome and MFA error\n * code.\n *\n * @param name - Span name.\n * @param operation - Caller-supplied `reason.operation`.\n * @param credentialType - Credential type the step concerns.\n * @param fn - The network step.\n * @returns The step's result.\n */\n async #runMfaRequest<Result>(\n name: string,\n operation: string,\n credentialType: string,\n fn: () => Promise<Result>,\n ): Promise<Result> {\n return await this.#trace(\n {\n name,\n tags: { operation, credentialType },\n },\n async (context) => {\n try {\n const result = await fn();\n this.#setTraceAttribute(context, 'outcome', 'success');\n return result;\n } catch (error) {\n this.#setTraceAttribute(context, 'outcome', 'error');\n const mfaCode = getMfaErrorCode(error);\n if (mfaCode) {\n this.#setTraceAttribute(context, 'mfaErrorCode', mfaCode);\n if (mfaCode === 'authentication_required' && this.#isUnlocked) {\n this.#invalidateSrpSession(this.#getPrimaryEntropySourceId());\n // A verification session must not outlive a rejected base\n // session.\n this.clearVerificationSession();\n }\n }\n throw error;\n }\n },\n );\n }\n\n /**\n * `TraceContext` is opaque in `@metamask/controller-utils`; both clients\n * hand back a Sentry span, so attributes are set via duck typing and a\n * non-Sentry context is a silent no-op.\n *\n * @param context - Span handed to the trace callback, if any.\n * @param key - Attribute name.\n * @param value - Attribute value.\n */\n #setTraceAttribute(\n context: TraceContext | undefined,\n key: string,\n value: string,\n ): void {\n const traceSpan = context as\n | { setAttribute?: (attribute: string, data: string) => void }\n | undefined;\n traceSpan?.setAttribute?.(key, value);\n }\n\n /**\n * Refreshes credentials enrolled on the canonical profile.\n *\n * @returns The current supported credentials.\n */\n public async refreshEnrolledCredentials(): Promise<EnrolledCredential[]> {\n this.#assertIsUnlocked('refreshEnrolledCredentials');\n const sessionEpoch = this.#authSessionEpoch;\n this.#credentialsRefreshSeq += 1;\n const refreshSeq = this.#credentialsRefreshSeq;\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n const credentials = await this.#runMfaRequest(\n 'MFA Credentials Refresh',\n 'credentials.refresh',\n 'all',\n async () => await this.#auth.getMfaCredentials(primaryEntropySourceId),\n );\n this.#assertAuthSessionEpoch(sessionEpoch, 'refreshEnrolledCredentials');\n\n // A newer refresh started while this one was in flight; its result is at\n // least as fresh, so defer to it rather than overwrite with older data.\n if (refreshSeq !== this.#credentialsRefreshSeq) {\n return this.#getEnrolledCredentials();\n }\n\n // Skip the write when nothing changed so subscribers are not woken up by\n // a fresh-but-identical array.\n if (\n JSON.stringify(credentials) !==\n JSON.stringify(this.#getEnrolledCredentials())\n ) {\n this.update((state) => {\n state.enrolledCredentials = credentials;\n });\n }\n return credentials;\n }\n\n /**\n * Begins enrollment of a passkey or email OTP credential.\n *\n * @param request - Credential, optional email address, and trace reason.\n * @returns A challenge for the client-owned ceremony.\n */\n public async beginCredentialEnrollment(\n request: BeginEnrollmentRequest,\n ): Promise<EnrollmentChallenge> {\n this.#assertIsUnlocked('beginCredentialEnrollment');\n const sessionEpoch = this.#authSessionEpoch;\n assertValidMfaRequest(request, BeginEnrollmentRequestStruct);\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n // The server requires AAL2 to add a credential once one that proves AAL2\n // exists: send the verification token only while a recent enough session\n // is live and let the server decide. An older session stays open for\n // other consumers.\n const accessToken = this.getVerificationToken({\n maxSessionAgeMs: request.maxSessionAgeMs ?? ENROLLMENT_MAX_SESSION_AGE_MS,\n })?.accessToken;\n const challenge = await this.#runMfaRequest(\n 'MFA Enroll Begin',\n request.reason.operation,\n request.type,\n async () =>\n await this.#auth.beginMfaEnrollment(request.type, {\n email: request.email,\n entropySourceId: primaryEntropySourceId,\n accessToken,\n }),\n );\n this.#assertAuthSessionEpoch(sessionEpoch, 'beginCredentialEnrollment');\n return challenge;\n }\n\n /**\n * Completes credential enrollment and refreshes the credential cache.\n *\n * A cache-refresh failure does not undo successful enrollment. Email\n * enrollment invalidates the primary SRP session *after* refresh so the\n * credentials call can reuse the still-valid access token; the next token\n * fetch then includes the newly verified email claim. That invalidation\n * happens even if the session ends mid-request: the enrollment succeeded\n * on the server, so a token cached across a lock must not be reused\n * without the new claim.\n *\n * @param request - Flow identifier, platform or email proof, and trace reason.\n * @returns The refreshed credentials, or the existing cache if refresh fails.\n */\n public async completeCredentialEnrollment(\n request: CompleteEnrollmentRequest,\n ): Promise<EnrolledCredential[]> {\n this.#assertIsUnlocked('completeCredentialEnrollment');\n const sessionEpoch = this.#authSessionEpoch;\n assertValidMfaRequest(request, CompleteEnrollmentRequestStruct);\n const { type } = request.proof;\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n await this.#runMfaRequest(\n 'MFA Enroll Complete',\n request.reason.operation,\n type,\n async () =>\n await this.#auth.completeMfaEnrollment(\n request.flowId,\n request.proof,\n primaryEntropySourceId,\n ),\n );\n\n try {\n this.#assertAuthSessionEpoch(\n sessionEpoch,\n 'completeCredentialEnrollment',\n );\n } catch (error) {\n if (type === 'email_otp') {\n this.#invalidateSrpSession(primaryEntropySourceId);\n }\n throw error;\n }\n\n // The verification session is deliberately kept: adding a factor does not\n // weaken an earlier proof, and `beginCredentialEnrollment` already limits\n // which sessions may add the next one.\n try {\n return await this.refreshEnrolledCredentials();\n } catch {\n return this.#getEnrolledCredentials();\n } finally {\n if (type === 'email_otp') {\n this.#invalidateSrpSession(primaryEntropySourceId);\n }\n }\n }\n\n /**\n * Begins verification with an enrolled credential.\n *\n * @param request - Credential type and trace reason.\n * @returns A challenge for the client-owned ceremony.\n */\n public async beginCredentialVerification(\n request: BeginVerificationRequest,\n ): Promise<VerificationChallenge> {\n this.#assertIsUnlocked('beginCredentialVerification');\n const sessionEpoch = this.#authSessionEpoch;\n assertValidMfaRequest(request, BeginVerificationRequestStruct);\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n const challenge = await this.#runMfaRequest(\n 'MFA Verification Begin',\n request.reason.operation,\n request.type,\n async () =>\n await this.#auth.beginMfaVerification(\n request.type,\n primaryEntropySourceId,\n ),\n );\n this.#assertAuthSessionEpoch(sessionEpoch, 'beginCredentialVerification');\n return challenge;\n }\n\n /**\n * Completes verification and opens a short-lived verification session.\n *\n * The assertion returned by the MFA service is exchanged at Hydra for an\n * access token. Its assurance level is not checked: the services receiving\n * the token enforce their own requirements. The token itself never enters\n * controller state.\n *\n * @param request - Flow identifier, platform or email proof, and trace reason.\n * @returns The verification token.\n */\n public async completeCredentialVerification(\n request: CompleteVerificationRequest,\n ): Promise<VerificationToken> {\n this.#assertIsUnlocked('completeCredentialVerification');\n const sessionEpoch = this.#authSessionEpoch;\n assertValidMfaRequest(request, CompleteVerificationRequestStruct);\n const { type } = request.proof;\n const { operation } = request.reason;\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n const assertion = await this.#runMfaRequest(\n 'MFA Verification Complete',\n operation,\n type,\n async () =>\n await this.#auth.completeMfaVerification(\n request.flowId,\n request.proof,\n primaryEntropySourceId,\n ),\n );\n this.#assertAuthSessionEpoch(\n sessionEpoch,\n 'completeCredentialVerification',\n );\n const accessToken = await this.#runMfaRequest(\n 'MFA Token Exchange',\n operation,\n type,\n async () => await this.#auth.exchangeMfaAssertion(assertion.token),\n );\n this.#assertAuthSessionEpoch(\n sessionEpoch,\n 'completeCredentialVerification',\n );\n\n let decodedClaims: unknown;\n try {\n decodedClaims = decodeJwtPayload(accessToken.accessToken);\n } catch (error) {\n throw new VerificationTokenInvalidError(toErrorMessage(error));\n }\n const claims = parseVerificationTokenClaims(decodedClaims);\n if (claims.exp * 1000 <= Date.now()) {\n throw new VerificationTokenInvalidError('Verification token is expired');\n }\n\n const token: VerificationToken = { ...accessToken, claims };\n this.#openVerificationSession(token);\n return token;\n }\n\n /**\n * Returns the active verification token when it meets the requested\n * freshness.\n *\n * @param request - Optional maximum session age in milliseconds, measured\n * from when the token was obtained. Zero always requires a new ceremony.\n * @returns A live verification token, or null when no reusable session\n * exists.\n */\n public getVerificationToken(\n request: GetVerificationTokenRequest = {},\n ): VerificationToken | null {\n this.#assertIsUnlocked('getVerificationToken');\n assertValidMfaRequest(request, GetVerificationTokenRequestStruct);\n const session = this.#verificationSessions.get(DEFAULT_AUDIENCE);\n if (!session) {\n return null;\n }\n const now = Date.now();\n if (now >= session.expiresAt) {\n // The hard-expiry timer has not fired yet (e.g. a suspended tab).\n this.#dropVerificationSession(DEFAULT_AUDIENCE);\n return null;\n }\n // `>=` so a zero max age always forces a fresh ceremony. Not cleared: the\n // max age is this caller's requirement; others may still use the session.\n const maxAge = request.maxSessionAgeMs;\n if (maxAge !== undefined && now - session.token.obtainedAt >= maxAge) {\n return null;\n }\n return session.token;\n }\n\n /**\n * Opens the verification session. Its lifetime is the session TTL clamped to\n * the token's own `exp`, so the session never outlives the token.\n *\n * @param token - The freshly exchanged verification token.\n */\n #openVerificationSession(token: VerificationToken): void {\n const audience = DEFAULT_AUDIENCE;\n this.#dropVerificationSession(audience);\n const expiresAt = Math.min(\n token.obtainedAt + VERIFICATION_SESSION_TTL_MS,\n token.claims.exp * 1000,\n );\n const timer = setTimeout(\n () => this.#dropVerificationSession(audience),\n Math.max(0, expiresAt - Date.now()),\n );\n // Never keep a Node process alive for the expiry timer (tests, tooling).\n (timer as { unref?: () => void }).unref?.();\n this.#verificationSessions.set(audience, { token, expiresAt, timer });\n }\n\n /**\n * Drops one audience's verification session and its expiration timer.\n *\n * @param audience - Audience whose session to drop.\n */\n #dropVerificationSession(audience: string): void {\n const session = this.#verificationSessions.get(audience);\n if (session) {\n clearTimeout(session.timer);\n this.#verificationSessions.delete(audience);\n }\n }\n\n /**\n * Clears every in-memory verification session and its expiration timer.\n */\n public clearVerificationSession(): void {\n for (const { timer } of this.#verificationSessions.values()) {\n clearTimeout(timer);\n }\n this.#verificationSessions.clear();\n }\n\n /**\n * Drops the cached credential list. Callers that wipe profile state must go\n * through this so subscribers never keep credentials belonging to a profile\n * that is no longer active.\n */\n #clearEnrolledCredentials(): void {\n if (this.#getEnrolledCredentials().length === 0) {\n return;\n }\n this.update((state) => {\n state.enrolledCredentials = [];\n });\n }\n\n #getEnrolledCredentials(): EnrolledCredential[] {\n return this.state.enrolledCredentials ?? [];\n }\n\n public performSignOut(): void {\n this.#authSessionEpoch += 1;\n this.clearVerificationSession();\n this.#clearEnrolledCredentials();\n this.update((state) => {\n state.isSignedIn = false;\n state.srpSessionData = undefined;\n });\n }\n\n /**\n * Resets the controller to `defaultState`. Clients call this on wallet reset\n * so the next wallet starts unsigned with both pairing gates re-armed.\n */\n public clearState(): void {\n this.#profilePairingRequestEpoch += 1;\n this.#authSessionEpoch += 1;\n this.clearVerificationSession();\n this.#clearEnrolledCredentials();\n this.update(() => ({ ...defaultState }));\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 /**\n * Mints a partner identity token for the specified SRP, logging in if needed.\n *\n * Calls `POST /api/v2/oidc/token` with the Hydra login bearer and returns\n * the minted `access_token`. Email on live tokens is under JWT `ext`.\n * HTTP 422 throws `EmailRequiredError` when this profile has no\n * verified email.\n *\n * @param claims - Claim names to embed. Only `email` is supported.\n * @param audience - Partner audience (`kyc` or `iron`).\n * @param entropySourceId - The entropy source ID. Omit for the primary SRP.\n * @returns The partner identity access token.\n */\n public async getPartnerIdentityToken(\n claims: OidcTokenClaims,\n audience: OidcTokenAudience,\n entropySourceId?: string,\n ): Promise<string> {\n this.#assertIsUnlocked('getPartnerIdentityToken');\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n return await this.#auth.getPartnerIdentityToken(\n claims,\n audience,\n resolvedId,\n );\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
+ {"version":3,"file":"AuthenticationController.js","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAO3D,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAc/E,OAAO,EACL,4BAA4B,EAC5B,+BAA+B,EAC/B,qBAAqB,EACrB,8BAA8B,EAC9B,iCAAiC,EACjC,iCAAiC,EACjC,4BAA4B,GAC7B,MAAM,oDAAoD,CAAC;AAsB5D,OAAO,EACL,+BAA+B,EAC/B,QAAQ,EACR,GAAG,EACH,aAAa,EACb,iBAAiB,EACjB,eAAe,EACf,6BAA6B,GAC9B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAC;AAErE,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AACzE,OAAO,EACL,0BAA0B,EAC1B,gCAAgC,GACjC,MAAM,uCAAuC,CAAC;AAG/C,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAsClD,MAAM,CAAC,MAAM,YAAY,GAAkC;IACzD,UAAU,EAAE,KAAK;IACjB,mBAAmB,EAAE,EAAE;IACvB,mBAAmB,EAAE,IAAI;IACzB,kBAAkB,EAAE,IAAI;CACzB,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,kBA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-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type { TraceCallback, TraceContext } from '@metamask/controller-utils';\nimport { selectHdKeyringEntropySourceIds } from '@metamask/keyring-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n KeyringControllerWithKeyringV2UnsafeAction,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\n SeedlessOnboardingControllerGetAccessTokenAction,\n SeedlessOnboardingControllerGetStateAction,\n} from '@metamask/seedless-onboarding-controller';\nimport type { Json } from '@metamask/utils';\n\nimport {\n BeginEnrollmentRequestStruct,\n CompleteEnrollmentRequestStruct,\n assertValidMfaRequest,\n BeginVerificationRequestStruct,\n CompleteVerificationRequestStruct,\n GetVerificationTokenRequestStruct,\n parseVerificationTokenClaims,\n} from '../../sdk/authentication-jwt-bearer/mfa/schemas.js';\nimport type {\n LoginIdentifierType,\n LoginResponse,\n ProfileAlias,\n ProfileIdentifier,\n SRPInterface,\n SrpLoginTag,\n UserProfile,\n UserProfileLineage,\n OidcTokenAudience,\n OidcTokenClaims,\n BeginEnrollmentRequest,\n CompleteEnrollmentRequest,\n EnrolledCredential,\n EnrollmentChallenge,\n BeginVerificationRequest,\n CompleteVerificationRequest,\n VerificationToken,\n GetVerificationTokenRequest,\n VerificationChallenge,\n} from '../../sdk/index.js';\nimport {\n assertMessageStartsWithMetamask,\n AuthType,\n Env,\n JwtBearerAuth,\n PairConflictError,\n getMfaErrorCode,\n VerificationTokenInvalidError,\n} from '../../sdk/index.js';\nimport { decodeJwtPayload } from '../../sdk/utils/jwt.js';\nimport { toErrorMessage } from '../../sdk/utils/to-error-message.js';\nimport type { MetaMetricsAuth } from '../../shared/types/services.js';\nimport { getPrimaryHdKeyringEntropySourceId } 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 * Credentials fetched for the current profile. The controller always seeds\n * this to an empty array; it remains optional so partial-state selectors stay\n * assignable to the controller state type.\n */\n enrolledCredentials?: EnrolledCredential[];\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 /**\n * Client gate for social identifier pairing. Defaults to `true` (fresh\n * install / upgrade), set to `false` after a successful or 409\n * `POST /api/v2/profile/pair/identifier`, left `true` on other failures\n * so the next `performSignIn` retries, and cleared without an API call\n * when the user never logged in with a social provider.\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 needsSocialPairing?: boolean;\n};\nexport const defaultState: AuthenticationControllerState = {\n isSignedIn: false,\n enrolledCredentials: [],\n needsProfilePairing: true,\n needsSocialPairing: 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 needsSocialPairing: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n srpSessionData: {\n // Remove access token and paired identifiers 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 const {\n pairedIdentifierIds: _unusedPairedIdentifierIds,\n ...profileWithoutPairedIdentifierIds\n } = value.profile;\n sanitizedSrpSessionData[key] = {\n ...value,\n token: tokenWithoutAccessToken,\n profile: profileWithoutPairedIdentifierIds,\n };\n return sanitizedSrpSessionData;\n },\n {},\n );\n },\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n enrolledCredentials: {\n // Allow-list so new credential types cannot leak identifiers by default.\n includeInStateLogs: (credentials) =>\n credentials?.map(({ type, status, enrolledAt }) => ({\n type,\n status,\n ...(enrolledAt === undefined ? {} : { enrolledAt }),\n })) ?? null,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\n/**\n * Upper bound on a verification session's lifetime. The session also ends at\n * the verification token's own `exp` (15 minutes today), whichever comes\n * first, so this only matters if the server ever issues longer-lived tokens.\n * Callers needing a fresher proof pass `maxSessionAgeMs` to\n * `getVerificationToken`.\n */\nexport const VERIFICATION_SESSION_TTL_MS = 15 * 60_000;\n\n/**\n * Default maximum age of a verification session that may authorize enrolling a\n * credential. A session opened for an unrelated operation must not be able to\n * add a factor long after the fact, while a session proven moments ago (or\n * during the same setup flow, via `maxSessionAgeMs`) may.\n */\nexport const ENROLLMENT_MAX_SESSION_AGE_MS = 2 * 60_000;\n\n/**\n * Key of the only verification session held today. Sessions are keyed by token\n * audience so audience-scoped tokens can be added without reshaping storage.\n */\nconst DEFAULT_AUDIENCE = '';\n\ntype VerificationSession = {\n token: VerificationToken;\n expiresAt: number;\n timer: ReturnType<typeof setTimeout>;\n};\ntype ControllerConfig = {\n env: Env;\n /**\n * When `true`, `performSignIn` attempts to attach the Google/Apple/\n * Telegram social identifier to the primary SRP profile. Defaults to\n * `() => false`.\n */\n isSocialPairingEnabled: () => boolean;\n};\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'performSignIn',\n 'performSignOut',\n 'getBearerToken',\n 'getSessionProfile',\n 'refreshCanonicalProfileId',\n 'getUserProfileLineage',\n 'getCustomerServiceToken',\n 'getPartnerIdentityToken',\n 'isSignedIn',\n 'requestProfilePairing',\n 'clearState',\n 'refreshEnrolledCredentials',\n 'beginCredentialEnrollment',\n 'completeCredentialEnrollment',\n 'beginCredentialVerification',\n 'completeCredentialVerification',\n 'getVerificationToken',\n 'clearVerificationSession',\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 | SeedlessOnboardingControllerGetAccessTokenAction;\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 #trace: TraceCallback;\n\n readonly #config: ControllerConfig = {\n env: Env.PRD,\n isSocialPairingEnabled: () => false,\n };\n\n #isUnlocked = false;\n\n /**\n * Bumped whenever the authenticated session ends, so an in-flight MFA\n * ceremony started under the previous session cannot apply its result.\n */\n #authSessionEpoch = 0;\n\n /**\n * Verification sessions keyed by token audience. At most one session per\n * audience; only `DEFAULT_AUDIENCE` is used until audience-scoped tokens\n * exist.\n */\n readonly #verificationSessions = new Map<string, VerificationSession>();\n\n /**\n * Sequence number of the most recently started credentials refresh. Only\n * that refresh may write the cache, so a slower, earlier request cannot\n * overwrite a newer list (e.g. an explicit refresh landing after an\n * enrollment's refresh).\n */\n #credentialsRefreshSeq = 0;\n\n /**\n * Bumped by `requestProfilePairing` and `clearState` so an in-flight\n * `performSignIn` can't clear `needsProfilePairing` afterwards.\n */\n #profilePairingRequestEpoch = 0;\n\n /**\n * Sign-in currently running. Overlapping callers share it.\n */\n #ongoingSignIn?: Promise<string[]>;\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.#authSessionEpoch += 1;\n this.#isUnlocked = false;\n this.clearVerificationSession();\n });\n },\n };\n\n constructor({\n messenger,\n state,\n config,\n metametrics,\n trace,\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 trace?: TraceCallback;\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 // `??` per key so an explicit `undefined` keeps the default rather than\n // clobbering it.\n this.#config = {\n env: config?.env ?? this.#config.env,\n isSocialPairingEnabled:\n config?.isSocialPairingEnabled ?? this.#config.isSocialPairingEnabled,\n };\n\n this.#metametrics = metametrics;\n this.#trace = trace ?? (((_request, fn) => fn?.()) as TraceCallback);\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 // The API omits `paired_identifier_ids` when it fails to load them, so\n // keep the last known value rather than wiping it.\n const pairedIdentifierIds =\n loginResponse.profile.pairedIdentifierIds ??\n state.srpSessionData[resolvedId]?.profile.pairedIdentifierIds;\n state.srpSessionData[resolvedId] = {\n ...loginResponse,\n profile: {\n ...loginResponse.profile,\n metaMetricsId,\n ...(pairedIdentifierIds ? { pairedIdentifierIds } : {}),\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 #assertAuthSessionEpoch(epoch: number, methodName: string): void {\n if (!this.#isUnlocked || this.#authSessionEpoch !== epoch) {\n throw new Error(\n `${methodName} - unable to proceed, the authenticated session ended`,\n );\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 keyringState = this.messenger.call('KeyringController:getState');\n return selectHdKeyringEntropySourceIds(keyringState);\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 keyringState = this.messenger.call('KeyringController:getState');\n return getPrimaryHdKeyringEntropySourceId(keyringState);\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 return this.#identifierTypeFromSeedlessState(\n this.messenger.call('SeedlessOnboardingController:getState'),\n );\n } catch {\n return 'SRP';\n }\n }\n\n /**\n * Maps SeedlessOnboarding vault + `authConnection` to a login identifier\n * type. Does not catch messenger errors — callers decide whether a\n * missing controller is `SRP` or a retryable failure.\n *\n * @param state - SeedlessOnboarding slice used for the mapping.\n * @param state.vault - Encrypted social vault, if present.\n * @param state.authConnection - Social provider id (`google` / `apple` /\n * `telegram`).\n * @returns The social provider identifier type, or `SRP`.\n */\n #identifierTypeFromSeedlessState(state: {\n vault?: string | null;\n authConnection?: string;\n }): LoginIdentifierType {\n if (state.vault === null || state.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 (state.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 }\n\n public async performSignIn(): Promise<string[]> {\n this.#assertIsUnlocked('performSignIn');\n if (this.#ongoingSignIn) {\n return await this.#ongoingSignIn;\n }\n\n const signIn = this.#runPerformSignIn().finally(() => {\n if (this.#ongoingSignIn === signIn) {\n this.#ongoingSignIn = undefined;\n }\n });\n\n this.#ongoingSignIn = signIn;\n return await signIn;\n }\n\n async #runPerformSignIn(): Promise<string[]> {\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 try {\n await this.#trySocialPairing(accessTokens[0]);\n } catch {\n // noop\n }\n\n return accessTokens;\n }\n\n /**\n * Attaches a Google/Apple/Telegram social identifier to the primary SRP\n * profile via `POST /api/v2/profile/pair/identifier`.\n *\n * Runs only when `isSocialPairingEnabled()` is true and\n * `needsSocialPairing` is not `false` (`undefined` is treated as true).\n * No social provider (`authConnection` unset) → clear the flag (nothing\n * to pair). Social provider set but vault missing → skip (onboarding\n * still in flight). Google without email → skip (API requires it).\n * Telegram never sends `email` (the field holds a display name, not an\n * address). Missing social JWT → skip. 409 Conflict → clear the flag\n * (identifier already owned; retry is pointless). Other errors\n * propagate so the caller can swallow them and leave the flag set for\n * retry.\n *\n * @param primaryAccessToken - Primary SRP OIDC access token used as the\n * Bearer credential. The profile associated with this JWT becomes the\n * canonical owner of the social identifier.\n */\n async #trySocialPairing(primaryAccessToken?: string): Promise<void> {\n if (\n !this.#config.isSocialPairingEnabled() ||\n this.state.needsSocialPairing === false ||\n !primaryAccessToken\n ) {\n return;\n }\n\n let seedlessState: {\n vault?: string | null;\n authConnection?: string;\n socialLoginEmail?: string;\n };\n try {\n seedlessState = this.messenger.call(\n 'SeedlessOnboardingController:getState',\n );\n } catch {\n // Controller missing or getState failed — retry next performSignIn.\n return;\n }\n\n // `SRP` here does not describe the vault: it is the mapping's \"no social\n // identity\" result, returned when there is no seedless vault or the\n // provider is unrecognised. In both cases there is nothing to pair.\n const identifierType = this.#identifierTypeFromSeedlessState(seedlessState);\n if (identifierType === 'SRP') {\n const { vault, authConnection } = seedlessState;\n // Vault not written yet but a social provider is already known —\n // onboarding is still in flight. Do not clear; retry next sign-in.\n if ((vault === null || vault === undefined) && Boolean(authConnection)) {\n return;\n }\n this.#clearNeedsSocialPairing();\n return;\n }\n\n // Email policy follows the API contract: GOOGLE requires `email` (400\n // without it), APPLE accepts it optionally, TELEGRAM must not send it\n // (clients store a display name in `socialLoginEmail` for Telegram).\n // Clients request the `email` scope for Google, so a missing value is a\n // defensive case rather than an expected one; returning here leaves\n // `needsSocialPairing` set so the next sign-in retries instead of\n // sending a request that would fail.\n const { socialLoginEmail } = seedlessState;\n let email: string | undefined;\n if (identifierType === 'GOOGLE') {\n if (!socialLoginEmail) {\n return;\n }\n email = socialLoginEmail;\n } else if (identifierType === 'APPLE') {\n email = socialLoginEmail;\n }\n\n const socialJwt = await this.messenger.call(\n 'SeedlessOnboardingController:getAccessToken',\n );\n if (socialJwt === undefined || socialJwt === '') {\n return;\n }\n\n try {\n const pairedIdentifierIds = await this.#auth.pairSocialIdentifier(\n {\n identifierType,\n socialJwt,\n ...(email ? { email } : {}),\n },\n primaryAccessToken,\n );\n this.#setPrimaryPairedIdentifierIds(pairedIdentifierIds);\n this.#clearNeedsSocialPairing();\n } catch (error) {\n if (error instanceof PairConflictError) {\n this.#clearNeedsSocialPairing();\n return;\n }\n throw error;\n }\n }\n\n #clearNeedsSocialPairing(): void {\n if (this.state.needsSocialPairing !== false) {\n this.update((state) => {\n state.needsSocialPairing = false;\n });\n }\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, pairedIdentifierIds },\n } = await this.#auth.pairSrpProfiles(accessTokens, primaryAccessToken);\n this.#propagateCanonical(canonicalProfileId);\n this.#setPrimaryPairedIdentifierIds(pairedIdentifierIds);\n return profileAliases;\n }\n\n /**\n * Pair calls use the primary SRP's token, so their response only describes\n * the primary's profile: secondaries skipped by the server are not in it.\n *\n * @param pairedIdentifierIds - Identifiers returned by the pair call, if any.\n */\n #setPrimaryPairedIdentifierIds(\n pairedIdentifierIds: ProfileIdentifier[] | undefined,\n ): void {\n if (!pairedIdentifierIds) {\n return;\n }\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n this.update((state) => {\n const entry = state.srpSessionData?.[primaryEntropySourceId];\n if (entry?.profile) {\n entry.profile.pairedIdentifierIds = pairedIdentifierIds;\n }\n });\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 /**\n * Runs one MFA network step inside a trace span tagged with the caller's\n * operation and the credential type, recording the outcome and MFA error\n * code.\n *\n * @param name - Span name.\n * @param operation - Caller-supplied `reason.operation`.\n * @param credentialType - Credential type the step concerns.\n * @param fn - The network step.\n * @returns The step's result.\n */\n async #runMfaRequest<Result>(\n name: string,\n operation: string,\n credentialType: string,\n fn: () => Promise<Result>,\n ): Promise<Result> {\n return await this.#trace(\n {\n name,\n tags: { operation, credentialType },\n },\n async (context) => {\n try {\n const result = await fn();\n this.#setTraceAttribute(context, 'outcome', 'success');\n return result;\n } catch (error) {\n this.#setTraceAttribute(context, 'outcome', 'error');\n const mfaCode = getMfaErrorCode(error);\n if (mfaCode) {\n this.#setTraceAttribute(context, 'mfaErrorCode', mfaCode);\n if (mfaCode === 'authentication_required' && this.#isUnlocked) {\n this.#invalidateSrpSession(this.#getPrimaryEntropySourceId());\n // A verification session must not outlive a rejected base\n // session.\n this.clearVerificationSession();\n }\n }\n throw error;\n }\n },\n );\n }\n\n /**\n * `TraceContext` is opaque in `@metamask/controller-utils`; both clients\n * hand back a Sentry span, so attributes are set via duck typing and a\n * non-Sentry context is a silent no-op.\n *\n * @param context - Span handed to the trace callback, if any.\n * @param key - Attribute name.\n * @param value - Attribute value.\n */\n #setTraceAttribute(\n context: TraceContext | undefined,\n key: string,\n value: string,\n ): void {\n const traceSpan = context as\n | { setAttribute?: (attribute: string, data: string) => void }\n | undefined;\n traceSpan?.setAttribute?.(key, value);\n }\n\n /**\n * Refreshes credentials enrolled on the canonical profile.\n *\n * @returns The current supported credentials.\n */\n public async refreshEnrolledCredentials(): Promise<EnrolledCredential[]> {\n this.#assertIsUnlocked('refreshEnrolledCredentials');\n const sessionEpoch = this.#authSessionEpoch;\n this.#credentialsRefreshSeq += 1;\n const refreshSeq = this.#credentialsRefreshSeq;\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n const credentials = await this.#runMfaRequest(\n 'MFA Credentials Refresh',\n 'credentials.refresh',\n 'all',\n async () => await this.#auth.getMfaCredentials(primaryEntropySourceId),\n );\n this.#assertAuthSessionEpoch(sessionEpoch, 'refreshEnrolledCredentials');\n\n // A newer refresh started while this one was in flight; its result is at\n // least as fresh, so defer to it rather than overwrite with older data.\n if (refreshSeq !== this.#credentialsRefreshSeq) {\n return this.#getEnrolledCredentials();\n }\n\n // Skip the write when nothing changed so subscribers are not woken up by\n // a fresh-but-identical array.\n if (\n JSON.stringify(credentials) !==\n JSON.stringify(this.#getEnrolledCredentials())\n ) {\n this.update((state) => {\n state.enrolledCredentials = credentials;\n });\n }\n return credentials;\n }\n\n /**\n * Begins enrollment of a passkey or email OTP credential.\n *\n * @param request - Credential, optional email address, and trace reason.\n * @returns A challenge for the client-owned ceremony.\n */\n public async beginCredentialEnrollment(\n request: BeginEnrollmentRequest,\n ): Promise<EnrollmentChallenge> {\n this.#assertIsUnlocked('beginCredentialEnrollment');\n const sessionEpoch = this.#authSessionEpoch;\n assertValidMfaRequest(request, BeginEnrollmentRequestStruct);\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n // The server requires AAL2 to add a credential once one that proves AAL2\n // exists: send the verification token only while a recent enough session\n // is live and let the server decide. An older session stays open for\n // other consumers.\n const accessToken = this.getVerificationToken({\n maxSessionAgeMs: request.maxSessionAgeMs ?? ENROLLMENT_MAX_SESSION_AGE_MS,\n })?.accessToken;\n const challenge = await this.#runMfaRequest(\n 'MFA Enroll Begin',\n request.reason.operation,\n request.type,\n async () =>\n await this.#auth.beginMfaEnrollment(request.type, {\n email: request.email,\n entropySourceId: primaryEntropySourceId,\n accessToken,\n }),\n );\n this.#assertAuthSessionEpoch(sessionEpoch, 'beginCredentialEnrollment');\n return challenge;\n }\n\n /**\n * Completes credential enrollment and refreshes the credential cache.\n *\n * A cache-refresh failure does not undo successful enrollment. Email\n * enrollment invalidates the primary SRP session *after* refresh so the\n * credentials call can reuse the still-valid access token; the next token\n * fetch then includes the newly verified email claim. That invalidation\n * happens even if the session ends mid-request: the enrollment succeeded\n * on the server, so a token cached across a lock must not be reused\n * without the new claim.\n *\n * @param request - Flow identifier, platform or email proof, and trace reason.\n * @returns The refreshed credentials, or the existing cache if refresh fails.\n */\n public async completeCredentialEnrollment(\n request: CompleteEnrollmentRequest,\n ): Promise<EnrolledCredential[]> {\n this.#assertIsUnlocked('completeCredentialEnrollment');\n const sessionEpoch = this.#authSessionEpoch;\n assertValidMfaRequest(request, CompleteEnrollmentRequestStruct);\n const { type } = request.proof;\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n await this.#runMfaRequest(\n 'MFA Enroll Complete',\n request.reason.operation,\n type,\n async () =>\n await this.#auth.completeMfaEnrollment(\n request.flowId,\n request.proof,\n primaryEntropySourceId,\n ),\n );\n\n try {\n this.#assertAuthSessionEpoch(\n sessionEpoch,\n 'completeCredentialEnrollment',\n );\n } catch (error) {\n if (type === 'email_otp') {\n this.#invalidateSrpSession(primaryEntropySourceId);\n }\n throw error;\n }\n\n // The verification session is deliberately kept: adding a factor does not\n // weaken an earlier proof, and `beginCredentialEnrollment` already limits\n // which sessions may add the next one.\n try {\n return await this.refreshEnrolledCredentials();\n } catch {\n return this.#getEnrolledCredentials();\n } finally {\n if (type === 'email_otp') {\n this.#invalidateSrpSession(primaryEntropySourceId);\n }\n }\n }\n\n /**\n * Begins verification with an enrolled credential.\n *\n * @param request - Credential type and trace reason.\n * @returns A challenge for the client-owned ceremony.\n */\n public async beginCredentialVerification(\n request: BeginVerificationRequest,\n ): Promise<VerificationChallenge> {\n this.#assertIsUnlocked('beginCredentialVerification');\n const sessionEpoch = this.#authSessionEpoch;\n assertValidMfaRequest(request, BeginVerificationRequestStruct);\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n const challenge = await this.#runMfaRequest(\n 'MFA Verification Begin',\n request.reason.operation,\n request.type,\n async () =>\n await this.#auth.beginMfaVerification(\n request.type,\n primaryEntropySourceId,\n ),\n );\n this.#assertAuthSessionEpoch(sessionEpoch, 'beginCredentialVerification');\n return challenge;\n }\n\n /**\n * Completes verification and opens a short-lived verification session.\n *\n * The assertion returned by the MFA service is exchanged at Hydra for an\n * access token. Its assurance level is not checked: the services receiving\n * the token enforce their own requirements. The token itself never enters\n * controller state.\n *\n * @param request - Flow identifier, platform or email proof, and trace reason.\n * @returns The verification token.\n */\n public async completeCredentialVerification(\n request: CompleteVerificationRequest,\n ): Promise<VerificationToken> {\n this.#assertIsUnlocked('completeCredentialVerification');\n const sessionEpoch = this.#authSessionEpoch;\n assertValidMfaRequest(request, CompleteVerificationRequestStruct);\n const { type } = request.proof;\n const { operation } = request.reason;\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n const assertion = await this.#runMfaRequest(\n 'MFA Verification Complete',\n operation,\n type,\n async () =>\n await this.#auth.completeMfaVerification(\n request.flowId,\n request.proof,\n primaryEntropySourceId,\n ),\n );\n this.#assertAuthSessionEpoch(\n sessionEpoch,\n 'completeCredentialVerification',\n );\n const accessToken = await this.#runMfaRequest(\n 'MFA Token Exchange',\n operation,\n type,\n async () => await this.#auth.exchangeMfaAssertion(assertion.token),\n );\n this.#assertAuthSessionEpoch(\n sessionEpoch,\n 'completeCredentialVerification',\n );\n\n let decodedClaims: unknown;\n try {\n decodedClaims = decodeJwtPayload(accessToken.accessToken);\n } catch (error) {\n throw new VerificationTokenInvalidError(toErrorMessage(error));\n }\n const claims = parseVerificationTokenClaims(decodedClaims);\n if (claims.exp * 1000 <= Date.now()) {\n throw new VerificationTokenInvalidError('Verification token is expired');\n }\n\n const token: VerificationToken = { ...accessToken, claims };\n this.#openVerificationSession(token);\n return token;\n }\n\n /**\n * Returns the active verification token when it meets the requested\n * freshness.\n *\n * @param request - Optional maximum session age in milliseconds, measured\n * from when the token was obtained. Zero always requires a new ceremony.\n * @returns A live verification token, or null when no reusable session\n * exists.\n */\n public getVerificationToken(\n request: GetVerificationTokenRequest = {},\n ): VerificationToken | null {\n this.#assertIsUnlocked('getVerificationToken');\n assertValidMfaRequest(request, GetVerificationTokenRequestStruct);\n const session = this.#verificationSessions.get(DEFAULT_AUDIENCE);\n if (!session) {\n return null;\n }\n const now = Date.now();\n if (now >= session.expiresAt) {\n // The hard-expiry timer has not fired yet (e.g. a suspended tab).\n this.#dropVerificationSession(DEFAULT_AUDIENCE);\n return null;\n }\n // `>=` so a zero max age always forces a fresh ceremony. Not cleared: the\n // max age is this caller's requirement; others may still use the session.\n const maxAge = request.maxSessionAgeMs;\n if (maxAge !== undefined && now - session.token.obtainedAt >= maxAge) {\n return null;\n }\n return session.token;\n }\n\n /**\n * Opens the verification session. Its lifetime is the session TTL clamped to\n * the token's own `exp`, so the session never outlives the token.\n *\n * @param token - The freshly exchanged verification token.\n */\n #openVerificationSession(token: VerificationToken): void {\n const audience = DEFAULT_AUDIENCE;\n this.#dropVerificationSession(audience);\n const expiresAt = Math.min(\n token.obtainedAt + VERIFICATION_SESSION_TTL_MS,\n token.claims.exp * 1000,\n );\n const timer = setTimeout(\n () => this.#dropVerificationSession(audience),\n Math.max(0, expiresAt - Date.now()),\n );\n // Never keep a Node process alive for the expiry timer (tests, tooling).\n (timer as { unref?: () => void }).unref?.();\n this.#verificationSessions.set(audience, { token, expiresAt, timer });\n }\n\n /**\n * Drops one audience's verification session and its expiration timer.\n *\n * @param audience - Audience whose session to drop.\n */\n #dropVerificationSession(audience: string): void {\n const session = this.#verificationSessions.get(audience);\n if (session) {\n clearTimeout(session.timer);\n this.#verificationSessions.delete(audience);\n }\n }\n\n /**\n * Clears every in-memory verification session and its expiration timer.\n */\n public clearVerificationSession(): void {\n for (const { timer } of this.#verificationSessions.values()) {\n clearTimeout(timer);\n }\n this.#verificationSessions.clear();\n }\n\n /**\n * Drops the cached credential list. Callers that wipe profile state must go\n * through this so subscribers never keep credentials belonging to a profile\n * that is no longer active.\n */\n #clearEnrolledCredentials(): void {\n if (this.#getEnrolledCredentials().length === 0) {\n return;\n }\n this.update((state) => {\n state.enrolledCredentials = [];\n });\n }\n\n #getEnrolledCredentials(): EnrolledCredential[] {\n return this.state.enrolledCredentials ?? [];\n }\n\n public performSignOut(): void {\n this.#authSessionEpoch += 1;\n this.clearVerificationSession();\n this.#clearEnrolledCredentials();\n this.update((state) => {\n state.isSignedIn = false;\n state.srpSessionData = undefined;\n });\n }\n\n /**\n * Resets the controller to `defaultState`. Clients call this on wallet reset\n * so the next wallet starts unsigned with both pairing gates re-armed.\n */\n public clearState(): void {\n this.#profilePairingRequestEpoch += 1;\n this.#authSessionEpoch += 1;\n this.clearVerificationSession();\n this.#clearEnrolledCredentials();\n this.update(() => ({ ...defaultState }));\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 /**\n * Mints a partner identity token for the specified SRP, logging in if needed.\n *\n * Calls `POST /api/v2/oidc/token` with the Hydra login bearer and returns\n * the minted `access_token`. Email on live tokens is under JWT `ext`.\n * HTTP 422 throws `EmailRequiredError` when this profile has no\n * verified email.\n *\n * @param claims - Claim names to embed. Only `email` is supported.\n * @param audience - Partner audience (`kyc` or `iron`).\n * @param entropySourceId - The entropy source ID. Omit for the primary SRP.\n * @returns The partner identity access token.\n */\n public async getPartnerIdentityToken(\n claims: OidcTokenClaims,\n audience: OidcTokenAudience,\n entropySourceId?: string,\n ): Promise<string> {\n this.#assertIsUnlocked('getPartnerIdentityToken');\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n return await this.#auth.getPartnerIdentityToken(\n claims,\n audience,\n resolvedId,\n );\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,7 +1,7 @@
1
1
  type CachedEntry = {
2
- salt: Uint8Array;
2
+ salt: Uint8Array<ArrayBuffer>;
3
3
  base64Salt: string;
4
- key: Uint8Array;
4
+ key: Uint8Array<ArrayBuffer>;
5
5
  };
6
6
  /**
7
7
  * Returns a given cached derived key from a hashed password and salt
@@ -10,7 +10,7 @@ type CachedEntry = {
10
10
  * @param salt - provide salt to receive cached key
11
11
  * @returns cached key
12
12
  */
13
- export declare function getCachedKeyBySalt(hashedPassword: string, salt: Uint8Array): CachedEntry | undefined;
13
+ export declare function getCachedKeyBySalt(hashedPassword: string, salt: Uint8Array<ArrayBuffer>): CachedEntry | undefined;
14
14
  /**
15
15
  * Gets the cached key that was generated without a salt, if it exists.
16
16
  * This is unique per hashed password.
@@ -27,6 +27,6 @@ export declare function getCachedKeyGeneratedWithSharedSalt(hashedPassword: stri
27
27
  * @param salt - salt to set new derived key
28
28
  * @param key - derived key we are setting
29
29
  */
30
- export declare function setCachedKey(hashedPassword: string, salt: Uint8Array, key: Uint8Array): void;
30
+ export declare function setCachedKey(hashedPassword: string, salt: Uint8Array<ArrayBuffer>, key: Uint8Array<ArrayBuffer>): void;
31
31
  export {};
32
32
  //# sourceMappingURL=cache.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../../../src/shared/encryption/cache.ts"],"names":[],"mappings":"AAGA,KAAK,WAAW,GAAG;IACjB,IAAI,EAAE,UAAU,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,UAAU,CAAC;CACjB,CAAC;AAiBF;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,UAAU,GACf,WAAW,GAAG,SAAS,CAazB;AAED;;;;;;GAMG;AACH,wBAAgB,mCAAmC,CACjD,cAAc,EAAE,MAAM,GACrB,WAAW,GAAG,SAAS,CAczB;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,UAAU,EAChB,GAAG,EAAE,UAAU,GACd,IAAI,CAeN"}
1
+ {"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../../../src/shared/encryption/cache.ts"],"names":[],"mappings":"AAGA,KAAK,WAAW,GAAG;IACjB,IAAI,EAAE,UAAU,CAAC,WAAW,CAAC,CAAC;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,UAAU,CAAC,WAAW,CAAC,CAAC;CAC9B,CAAC;AAiBF;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,UAAU,CAAC,WAAW,CAAC,GAC5B,WAAW,GAAG,SAAS,CAazB;AAED;;;;;;GAMG;AACH,wBAAgB,mCAAmC,CACjD,cAAc,EAAE,MAAM,GACrB,WAAW,GAAG,SAAS,CAczB;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,UAAU,CAAC,WAAW,CAAC,EAC7B,GAAG,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IACnB,CAAC;IAED,OAAO;QACL,IAAI,EAAE,WAAW;QACjB,UAAU;QACV,GAAG,EAAE,SAAS;KACf,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,YAAY,CAC1B,cAAsB,EACtB,IAAgB,EAChB,GAAe;IAEf,sBAAsB;IACtB,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,mBAAmB,EAAE,CAAC;QAC7D,cAAc,GAAG,EAAE,CAAC;IACtB,CAAC;IAED,MAAM,KAAK,GAAG,gBAAgB,CAAC,cAAc,CAAC,CAAC;IAC/C,MAAM,UAAU,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;IAE3C,kBAAkB;IAClB,IAAI,KAAK,CAAC,IAAI,GAAG,eAAe,EAAE,CAAC;QACjC,KAAK,CAAC,KAAK,EAAE,CAAC;IAChB,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["import { SHARED_SALT } from './constants.js';\nimport { byteArrayToBase64 } from './utils.js';\n\ntype CachedEntry = {\n salt: Uint8Array;\n base64Salt: string;\n key: Uint8Array;\n};\n\nconst MAX_PASSWORD_CACHES = 100;\nconst MAX_SALT_CACHES = 100;\n\n/**\n * In-Memory Caching derived keys based from a given salt and password.\n */\ntype PasswordMemCachedKDF = {\n [hashedPassword: string]: Map<string, Uint8Array>;\n};\nlet inMemCachedKDF: PasswordMemCachedKDF = {};\nconst getPasswordCache = (hashedPassword: string) => {\n inMemCachedKDF[hashedPassword] ??= new Map();\n return inMemCachedKDF[hashedPassword];\n};\n\n/**\n * Returns a given cached derived key from a hashed password and salt\n *\n * @param hashedPassword - hashed password for cache lookup\n * @param salt - provide salt to receive cached key\n * @returns cached key\n */\nexport function getCachedKeyBySalt(\n hashedPassword: string,\n salt: Uint8Array,\n): CachedEntry | undefined {\n const cache = getPasswordCache(hashedPassword);\n const base64Salt = byteArrayToBase64(salt);\n const cachedKey = cache.get(base64Salt);\n if (!cachedKey) {\n return undefined;\n }\n\n return {\n salt,\n base64Salt,\n key: cachedKey,\n };\n}\n\n/**\n * Gets the cached key that was generated without a salt, if it exists.\n * This is unique per hashed password.\n *\n * @param hashedPassword - hashed password for cache lookup\n * @returns the cached key\n */\nexport function getCachedKeyGeneratedWithSharedSalt(\n hashedPassword: string,\n): CachedEntry | undefined {\n const cache = getPasswordCache(hashedPassword);\n const base64Salt = byteArrayToBase64(SHARED_SALT);\n const cachedKey = cache.get(base64Salt);\n\n if (!cachedKey) {\n return undefined;\n }\n\n return {\n salt: SHARED_SALT,\n base64Salt,\n key: cachedKey,\n };\n}\n\n/**\n * Sets a key to the in memory cache.\n * We have set an arbitrary size of 10 cached keys per hashed password.\n *\n * @param hashedPassword - hashed password for cache lookup\n * @param salt - salt to set new derived key\n * @param key - derived key we are setting\n */\nexport function setCachedKey(\n hashedPassword: string,\n salt: Uint8Array,\n key: Uint8Array,\n): void {\n // Max password caches\n if (Object.keys(inMemCachedKDF).length > MAX_PASSWORD_CACHES) {\n inMemCachedKDF = {};\n }\n\n const cache = getPasswordCache(hashedPassword);\n const base64Salt = byteArrayToBase64(salt);\n\n // Max salt caches\n if (cache.size > MAX_SALT_CACHES) {\n cache.clear();\n }\n\n cache.set(base64Salt, key);\n}\n"]}
1
+ {"version":3,"file":"cache.js","sourceRoot":"","sources":["../../../src/shared/encryption/cache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAQ/C,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,MAAM,eAAe,GAAG,GAAG,CAAC;AAQ5B,IAAI,cAAc,GAAyB,EAAE,CAAC;AAC9C,MAAM,gBAAgB,GAAG,CAAC,cAAsB,EAAE,EAAE;IAClD,cAAc,CAAC,cAAc,CAAC,KAAK,IAAI,GAAG,EAAE,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,IAAI,KAAK,CAAC,IAAI,GAAG,eAAe,EAAE,CAAC;QACjC,KAAK,CAAC,KAAK,EAAE,CAAC;IAChB,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["import { SHARED_SALT } from './constants.js';\nimport { byteArrayToBase64 } from './utils.js';\n\ntype CachedEntry = {\n salt: Uint8Array<ArrayBuffer>;\n base64Salt: string;\n key: Uint8Array<ArrayBuffer>;\n};\n\nconst MAX_PASSWORD_CACHES = 100;\nconst MAX_SALT_CACHES = 100;\n\n/**\n * In-Memory Caching derived keys based from a given salt and password.\n */\ntype PasswordMemCachedKDF = {\n [hashedPassword: string]: Map<string, Uint8Array<ArrayBuffer>>;\n};\nlet inMemCachedKDF: PasswordMemCachedKDF = {};\nconst getPasswordCache = (hashedPassword: string) => {\n inMemCachedKDF[hashedPassword] ??= new Map();\n return inMemCachedKDF[hashedPassword];\n};\n\n/**\n * Returns a given cached derived key from a hashed password and salt\n *\n * @param hashedPassword - hashed password for cache lookup\n * @param salt - provide salt to receive cached key\n * @returns cached key\n */\nexport function getCachedKeyBySalt(\n hashedPassword: string,\n salt: Uint8Array<ArrayBuffer>,\n): CachedEntry | undefined {\n const cache = getPasswordCache(hashedPassword);\n const base64Salt = byteArrayToBase64(salt);\n const cachedKey = cache.get(base64Salt);\n if (!cachedKey) {\n return undefined;\n }\n\n return {\n salt,\n base64Salt,\n key: cachedKey,\n };\n}\n\n/**\n * Gets the cached key that was generated without a salt, if it exists.\n * This is unique per hashed password.\n *\n * @param hashedPassword - hashed password for cache lookup\n * @returns the cached key\n */\nexport function getCachedKeyGeneratedWithSharedSalt(\n hashedPassword: string,\n): CachedEntry | undefined {\n const cache = getPasswordCache(hashedPassword);\n const base64Salt = byteArrayToBase64(SHARED_SALT);\n const cachedKey = cache.get(base64Salt);\n\n if (!cachedKey) {\n return undefined;\n }\n\n return {\n salt: SHARED_SALT,\n base64Salt,\n key: cachedKey,\n };\n}\n\n/**\n * Sets a key to the in memory cache.\n * We have set an arbitrary size of 10 cached keys per hashed password.\n *\n * @param hashedPassword - hashed password for cache lookup\n * @param salt - salt to set new derived key\n * @param key - derived key we are setting\n */\nexport function setCachedKey(\n hashedPassword: string,\n salt: Uint8Array<ArrayBuffer>,\n key: Uint8Array<ArrayBuffer>,\n): void {\n // Max password caches\n if (Object.keys(inMemCachedKDF).length > MAX_PASSWORD_CACHES) {\n inMemCachedKDF = {};\n }\n\n const cache = getPasswordCache(hashedPassword);\n const base64Salt = byteArrayToBase64(salt);\n\n // Max salt caches\n if (cache.size > MAX_SALT_CACHES) {\n cache.clear();\n }\n\n cache.set(base64Salt, key);\n}\n"]}
@@ -1,4 +1,3 @@
1
- export declare const ALGORITHM_NONCE_SIZE = 12;
2
1
  export declare const ALGORITHM_KEY_SIZE = 16;
3
2
  export declare const SCRYPT_SALT_SIZE = 16;
4
3
  export declare const SCRYPT_N: number;
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/shared/encryption/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,oBAAoB,KAAK,CAAC;AACvC,eAAO,MAAM,kBAAkB,KAAK,CAAC;AAIrC,eAAO,MAAM,gBAAgB,KAAK,CAAC;AACnC,eAAO,MAAM,QAAQ,QAAU,CAAC;AAChC,eAAO,MAAM,QAAQ,IAAI,CAAC;AAC1B,eAAO,MAAM,QAAQ,IAAI,CAAC;AAE1B,eAAO,MAAM,WAAW,yBAEtB,CAAC;AAEH,eAAO,MAAM,0BAA0B,KAAK,CAAC"}
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/shared/encryption/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,kBAAkB,KAAK,CAAC;AAIrC,eAAO,MAAM,gBAAgB,KAAK,CAAC;AACnC,eAAO,MAAM,QAAQ,QAAU,CAAC;AAChC,eAAO,MAAM,QAAQ,IAAI,CAAC;AAC1B,eAAO,MAAM,QAAQ,IAAI,CAAC;AAE1B,eAAO,MAAM,WAAW,yBAEtB,CAAC;AAEH,eAAO,MAAM,0BAA0B,KAAK,CAAC"}
@@ -1,5 +1,3 @@
1
- // Nonce/Key Sizes
2
- export const ALGORITHM_NONCE_SIZE = 12; // 12 bytes
3
1
  export const ALGORITHM_KEY_SIZE = 16; // 16 bytes
4
2
  // Scrypt settings
5
3
  // see: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#scrypt
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/shared/encryption/constants.ts"],"names":[],"mappings":"AAAA,kBAAkB;AAClB,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,CAAC,CAAC,WAAW;AACnD,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,CAAC,CAAC,WAAW;AAEjD,kBAAkB;AAClB,+FAA+F;AAC/F,MAAM,CAAC,MAAM,gBAAgB,GAAG,EAAE,CAAC,CAAC,WAAW;AAC/C,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,wDAAwD;AACzF,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,uBAAuB;AAClD,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,4BAA4B;AAEvD,MAAM,CAAC,MAAM,WAAW,GAAG,IAAI,UAAU,CAAC;IACxC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;CACrD,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,0BAA0B,GAAG,EAAE,CAAC","sourcesContent":["// Nonce/Key Sizes\nexport const ALGORITHM_NONCE_SIZE = 12; // 12 bytes\nexport const ALGORITHM_KEY_SIZE = 16; // 16 bytes\n\n// Scrypt settings\n// see: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#scrypt\nexport const SCRYPT_SALT_SIZE = 16; // 16 bytes\nexport const SCRYPT_N = 2 ** 17; // CPU/memory cost parameter (must be a power of 2, > 1)\nexport const SCRYPT_r = 8; // Block size parameter\nexport const SCRYPT_p = 1; // Parallelization parameter\n\nexport const SHARED_SALT = new Uint8Array([\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n]);\n\nexport const MAX_KDF_PROMISE_CACHE_SIZE = 20;\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/shared/encryption/constants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,CAAC,CAAC,WAAW;AAEjD,kBAAkB;AAClB,+FAA+F;AAC/F,MAAM,CAAC,MAAM,gBAAgB,GAAG,EAAE,CAAC,CAAC,WAAW;AAC/C,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,wDAAwD;AACzF,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,uBAAuB;AAClD,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,4BAA4B;AAEvD,MAAM,CAAC,MAAM,WAAW,GAAG,IAAI,UAAU,CAAC;IACxC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;CACrD,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,0BAA0B,GAAG,EAAE,CAAC","sourcesContent":["export const ALGORITHM_KEY_SIZE = 16; // 16 bytes\n\n// Scrypt settings\n// see: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#scrypt\nexport const SCRYPT_SALT_SIZE = 16; // 16 bytes\nexport const SCRYPT_N = 2 ** 17; // CPU/memory cost parameter (must be a power of 2, > 1)\nexport const SCRYPT_r = 8; // Block size parameter\nexport const SCRYPT_p = 1; // Parallelization parameter\n\nexport const SHARED_SALT = new Uint8Array([\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n]);\n\nexport const MAX_KDF_PROMISE_CACHE_SIZE = 20;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"encryption.d.ts","sourceRoot":"","sources":["../../../src/shared/encryption/encryption.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAuB3D,MAAM,MAAM,gBAAgB,GAAG;IAE7B,CAAC,EAAE,GAAG,CAAC;IAGP,CAAC,EAAE,QAAQ,CAAC;IAGZ,CAAC,EAAE,MAAM,CAAC;IAGV,CAAC,EAAE;QACD,CAAC,EAAE,MAAM,CAAC;QACV,CAAC,EAAE,MAAM,CAAC;QACV,CAAC,EAAE,MAAM,CAAC;QACV,KAAK,EAAE,MAAM,CAAC;KACf,CAAC;IAGF,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,cAAM,kBAAkB;;IAOhB,aAAa,CACjB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,kBAAkB,CAAC,EAAE,YAAY,GAChC,OAAO,CAAC,MAAM,CAAC,CAWjB;IAEK,aAAa,CACjB,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,MAAM,EAChB,kBAAkB,CAAC,EAAE,YAAY,GAChC,OAAO,CAAC,MAAM,CAAC,CAmBjB;IAiFD,OAAO,CAAC,gBAAgB,EAAE,MAAM,2BAwB/B;IAED,8BAA8B,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAazD;CAqIF;AAED,QAAA,MAAM,UAAU,oBAA2B,CAAC;eAC7B,UAAU;AAEzB;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAGrD"}
1
+ {"version":3,"file":"encryption.d.ts","sourceRoot":"","sources":["../../../src/shared/encryption/encryption.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAsB3D,MAAM,MAAM,gBAAgB,GAAG;IAE7B,CAAC,EAAE,GAAG,CAAC;IAGP,CAAC,EAAE,QAAQ,CAAC;IAGZ,CAAC,EAAE,MAAM,CAAC;IAGV,CAAC,EAAE;QACD,CAAC,EAAE,MAAM,CAAC;QACV,CAAC,EAAE,MAAM,CAAC;QACV,CAAC,EAAE,MAAM,CAAC;QACV,KAAK,EAAE,MAAM,CAAC;KACf,CAAC;IAGF,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,cAAM,kBAAkB;;IAOhB,aAAa,CACjB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,kBAAkB,CAAC,EAAE,YAAY,GAChC,OAAO,CAAC,MAAM,CAAC,CAUjB;IAEK,aAAa,CACjB,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,MAAM,EAChB,kBAAkB,CAAC,EAAE,YAAY,GAChC,OAAO,CAAC,MAAM,CAAC,CAkBjB;IAiFD,OAAO,CAAC,gBAAgB,EAAE,MAAM,2BAuB/B;IAED,8BAA8B,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAazD;CAyIF;AAED,QAAA,MAAM,UAAU,oBAA2B,CAAC;eAC7B,UAAU;AAEzB;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAGrD"}
@@ -1,10 +1,9 @@
1
- import { gcm } from '@noble/ciphers/aes';
2
- import { randomBytes } from '@noble/ciphers/webcrypto';
1
+ import { decrypt, encrypt, IV_LENGTH } from '@metamask/cryptography/aes-gcm';
2
+ import { getErrorMessage, stringToBytes, bytesToHex, concatBytes, remove0x, } from '@metamask/utils';
3
3
  import { scryptAsync } from '@noble/hashes/scrypt';
4
4
  import { sha256 } from '@noble/hashes/sha256';
5
- import { utf8ToBytes, concatBytes, bytesToHex } from '@noble/hashes/utils';
6
5
  import { getCachedKeyBySalt, getCachedKeyGeneratedWithSharedSalt, setCachedKey, } from './cache.js';
7
- import { ALGORITHM_KEY_SIZE, ALGORITHM_NONCE_SIZE, MAX_KDF_PROMISE_CACHE_SIZE, SCRYPT_N, SCRYPT_p, SCRYPT_r, SCRYPT_SALT_SIZE, SHARED_SALT, } from './constants.js';
6
+ import { ALGORITHM_KEY_SIZE, MAX_KDF_PROMISE_CACHE_SIZE, SCRYPT_N, SCRYPT_p, SCRYPT_r, SCRYPT_SALT_SIZE, SHARED_SALT, } from './constants.js';
8
7
  import { base64ToByteArray, byteArrayToBase64, bytesToUtf8, stringToByteArray, } from './utils.js';
9
8
  class EncryptorDecryptor {
10
9
  // Promise cache for ongoing KDF operations to prevent duplicate work
@@ -14,8 +13,7 @@ class EncryptorDecryptor {
14
13
  return await this.#encryptStringV1(plaintext, password, nativeScryptCrypto);
15
14
  }
16
15
  catch (e) {
17
- const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
18
- throw new Error(`Unable to encrypt string - ${errorMessage}`);
16
+ throw new Error(`Unable to encrypt string - ${getErrorMessage(e)}`);
19
17
  }
20
18
  }
21
19
  async decryptString(encryptedDataStr, password, nativeScryptCrypto) {
@@ -29,8 +27,7 @@ class EncryptorDecryptor {
29
27
  throw new Error(`Unsupported encrypted data payload - ${encryptedDataStr}`);
30
28
  }
31
29
  catch (e) {
32
- const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
33
- throw new Error(`Unable to decrypt string - ${errorMessage}`);
30
+ throw new Error(`Unable to decrypt string - ${getErrorMessage(e)}`);
34
31
  }
35
32
  }
36
33
  async #encryptStringV1(plaintext, password, nativeScryptCrypto) {
@@ -41,8 +38,11 @@ class EncryptorDecryptor {
41
38
  dkLen: ALGORITHM_KEY_SIZE,
42
39
  }, undefined, nativeScryptCrypto);
43
40
  // Encrypt and prepend salt.
44
- const plaintextRaw = utf8ToBytes(plaintext);
45
- const ciphertextAndNonceAndSalt = concatBytes(salt, this.#encrypt(plaintextRaw, key));
41
+ const plaintextRaw = stringToBytes(plaintext);
42
+ const ciphertextAndNonceAndSalt = concatBytes([
43
+ salt,
44
+ await this.#encrypt(plaintextRaw, key),
45
+ ]);
46
46
  // Convert to Base64
47
47
  const encryptedData = byteArrayToBase64(ciphertextAndNonceAndSalt);
48
48
  const encryptedPayload = {
@@ -74,7 +74,7 @@ class EncryptorDecryptor {
74
74
  dkLen: o.dkLen,
75
75
  }, salt, nativeScryptCrypto);
76
76
  // Decrypt and return result.
77
- return bytesToUtf8(this.#decrypt(ciphertextAndNonce, key));
77
+ return bytesToUtf8(await this.#decrypt(ciphertextAndNonce, key));
78
78
  }
79
79
  getSalt(encryptedDataStr) {
80
80
  try {
@@ -92,8 +92,7 @@ class EncryptorDecryptor {
92
92
  throw new Error(`Unsupported encrypted data payload - ${encryptedDataStr}`);
93
93
  }
94
94
  catch (e) {
95
- const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
96
- throw new Error(`Unable to get salt - ${errorMessage}`);
95
+ throw new Error(`Unable to get salt - ${getErrorMessage(e)}`);
97
96
  }
98
97
  }
99
98
  getIfEntriesHaveDifferentSalts(entries) {
@@ -110,18 +109,17 @@ class EncryptorDecryptor {
110
109
  const strSet = new Set(salts.map((arr) => arr.toString()));
111
110
  return strSet.size === salts.length;
112
111
  }
113
- #encrypt(plaintext, key) {
114
- const nonce = randomBytes(ALGORITHM_NONCE_SIZE);
112
+ async #encrypt(plaintext, key) {
115
113
  // Encrypt and prepend nonce.
116
- const ciphertext = gcm(key, nonce).encrypt(plaintext);
117
- return concatBytes(nonce, ciphertext);
114
+ const { ciphertext, iv } = await encrypt(key, plaintext);
115
+ return concatBytes([iv, ciphertext]);
118
116
  }
119
- #decrypt(ciphertextAndNonce, key) {
117
+ async #decrypt(ciphertextAndNonce, key) {
120
118
  // Create buffers of nonce and ciphertext.
121
- const nonce = ciphertextAndNonce.slice(0, ALGORITHM_NONCE_SIZE);
122
- const ciphertext = ciphertextAndNonce.slice(ALGORITHM_NONCE_SIZE, ciphertextAndNonce.length);
119
+ const nonce = ciphertextAndNonce.slice(0, IV_LENGTH);
120
+ const ciphertext = ciphertextAndNonce.slice(IV_LENGTH, ciphertextAndNonce.length);
123
121
  // Decrypt and return result.
124
- return gcm(key, nonce).decrypt(ciphertext);
122
+ return decrypt(key, nonce, ciphertext);
125
123
  }
126
124
  async #getOrGenerateScryptKey(password, o, salt, nativeScryptCrypto) {
127
125
  const hashedPassword = createSHA256Hash(password);
@@ -173,12 +171,12 @@ class EncryptorDecryptor {
173
171
  newKey = await nativeScryptCrypto(stringToByteArray(password), salt, o.N, o.r, o.p, o.dkLen);
174
172
  }
175
173
  else {
176
- newKey = await scryptAsync(password, salt, {
174
+ newKey = (await scryptAsync(password, salt, {
177
175
  N: o.N,
178
176
  r: o.r,
179
177
  p: o.p,
180
178
  dkLen: o.dkLen,
181
- });
179
+ }));
182
180
  }
183
181
  setCachedKey(hashedPassword, salt, newKey);
184
182
  return {
@@ -197,6 +195,6 @@ export default encryption;
197
195
  */
198
196
  export function createSHA256Hash(data) {
199
197
  const hashedData = sha256(data);
200
- return bytesToHex(hashedData);
198
+ return remove0x(bytesToHex(hashedData));
201
199
  }
202
200
  //# sourceMappingURL=encryption.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"encryption.js","sourceRoot":"","sources":["../../../src/shared/encryption/encryption.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,oBAAoB,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,MAA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,MAAM,kBAAkB,CAC/B,iBAAiB,CAAC,QAAQ,CAAC,EAC3B,IAAI,EACJ,CAAC,CAAC,CAAC,EACH,CAAC,CAAC,CAAC,EACH,CAAC,CAAC,CAAC,EACH,CAAC,CAAC,KAAK,CACR,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,MAAM,GAAG,MAAM,WAAW,CAAC,QAAQ,EAAE,IAAI,EAAE;gBACzC,CAAC,EAAE,CAAC,CAAC,CAAC;gBACN,CAAC,EAAE,CAAC,CAAC,CAAC;gBACN,CAAC,EAAE,CAAC,CAAC,CAAC;gBACN,KAAK,EAAE,CAAC,CAAC,KAAK;aACf,CAAC,CAAC;QACL,CAAC;QAED,YAAY,CAAC,cAAc,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;QAE3C,OAAO;YACL,GAAG,EAAE,MAAM;YACX,IAAI;SACL,CAAC;IACJ,CAAC;CACF;AAED,MAAM,UAAU,GAAG,IAAI,kBAAkB,EAAE,CAAC;AAC5C,eAAe,UAAU,CAAC;AAE1B;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAAC,IAAY;IAC3C,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IAChC,OAAO,UAAU,CAAC,UAAU,CAAC,CAAC;AAChC,CAAC","sourcesContent":["import { gcm } from '@noble/ciphers/aes';\nimport { randomBytes } from '@noble/ciphers/webcrypto';\nimport { scryptAsync } from '@noble/hashes/scrypt';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { utf8ToBytes, concatBytes, bytesToHex } from '@noble/hashes/utils';\n\nimport type { NativeScrypt } from '../types/encryption.js';\nimport {\n getCachedKeyBySalt,\n getCachedKeyGeneratedWithSharedSalt,\n setCachedKey,\n} from './cache.js';\nimport {\n ALGORITHM_KEY_SIZE,\n ALGORITHM_NONCE_SIZE,\n MAX_KDF_PROMISE_CACHE_SIZE,\n SCRYPT_N,\n SCRYPT_p,\n SCRYPT_r,\n SCRYPT_SALT_SIZE,\n SHARED_SALT,\n} from './constants.js';\nimport {\n base64ToByteArray,\n byteArrayToBase64,\n bytesToUtf8,\n stringToByteArray,\n} from './utils.js';\n\nexport type EncryptedPayload = {\n // version\n v: '1';\n\n // key derivation function algorithm - scrypt\n t: 'scrypt';\n\n // data\n d: string;\n\n // encryption options - scrypt\n o: {\n N: number;\n r: number;\n p: number;\n dkLen: number;\n };\n\n // Salt options\n saltLen: number;\n};\n\nclass EncryptorDecryptor {\n // Promise cache for ongoing KDF operations to prevent duplicate work\n readonly #kdfPromiseCache = new Map<\n string,\n Promise<{ key: Uint8Array; salt: Uint8Array }>\n >();\n\n async encryptString(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n return await this.#encryptStringV1(\n plaintext,\n password,\n nativeScryptCrypto,\n );\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(`Unable to encrypt string - ${errorMessage}`);\n }\n }\n\n async decryptString(\n encryptedDataStr: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n return await this.#decryptStringV1(\n encryptedData,\n password,\n nativeScryptCrypto,\n );\n }\n }\n throw new Error(\n `Unsupported encrypted data payload - ${encryptedDataStr}`,\n );\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(`Unable to decrypt string - ${errorMessage}`);\n }\n }\n\n async #encryptStringV1(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n const { key, salt } = await this.#getOrGenerateScryptKey(\n password,\n {\n N: SCRYPT_N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n },\n undefined,\n nativeScryptCrypto,\n );\n\n // Encrypt and prepend salt.\n const plaintextRaw = utf8ToBytes(plaintext);\n const ciphertextAndNonceAndSalt = concatBytes(\n salt,\n this.#encrypt(plaintextRaw, key),\n );\n\n // Convert to Base64\n const encryptedData = byteArrayToBase64(ciphertextAndNonceAndSalt);\n\n const encryptedPayload: EncryptedPayload = {\n v: '1',\n t: 'scrypt',\n d: encryptedData,\n o: {\n N: SCRYPT_N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n },\n saltLen: SCRYPT_SALT_SIZE,\n };\n\n return JSON.stringify(encryptedPayload);\n }\n\n async #decryptStringV1(\n data: EncryptedPayload,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n const { o, d: base64CiphertextAndNonceAndSalt, saltLen } = data;\n\n // Decode the base64.\n const ciphertextAndNonceAndSalt = base64ToByteArray(\n base64CiphertextAndNonceAndSalt,\n );\n\n // Create buffers of salt and ciphertextAndNonce.\n const salt = ciphertextAndNonceAndSalt.slice(0, saltLen);\n const ciphertextAndNonce = ciphertextAndNonceAndSalt.slice(\n saltLen,\n ciphertextAndNonceAndSalt.length,\n );\n\n // Derive the key.\n const { key } = await this.#getOrGenerateScryptKey(\n password,\n {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n },\n salt,\n nativeScryptCrypto,\n );\n\n // Decrypt and return result.\n return bytesToUtf8(this.#decrypt(ciphertextAndNonce, key));\n }\n\n getSalt(encryptedDataStr: string) {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n const { d: base64CiphertextAndNonceAndSalt, saltLen } = encryptedData;\n\n // Decode the base64.\n const ciphertextAndNonceAndSalt = base64ToByteArray(\n base64CiphertextAndNonceAndSalt,\n );\n\n // Create buffers of salt and ciphertextAndNonce.\n const salt = ciphertextAndNonceAndSalt.slice(0, saltLen);\n return salt;\n }\n }\n throw new Error(\n `Unsupported encrypted data payload - ${encryptedDataStr}`,\n );\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(`Unable to get salt - ${errorMessage}`);\n }\n }\n\n getIfEntriesHaveDifferentSalts(entries: string[]): boolean {\n const salts = entries\n .map((e) => {\n try {\n return this.getSalt(e);\n } catch {\n return;\n }\n })\n .filter((s): s is Uint8Array<ArrayBuffer> => s !== undefined);\n\n const strSet = new Set(salts.map((arr) => arr.toString()));\n return strSet.size === salts.length;\n }\n\n #encrypt(plaintext: Uint8Array, key: Uint8Array): Uint8Array {\n const nonce = randomBytes(ALGORITHM_NONCE_SIZE);\n\n // Encrypt and prepend nonce.\n const ciphertext = gcm(key, nonce).encrypt(plaintext);\n\n return concatBytes(nonce, ciphertext);\n }\n\n #decrypt(ciphertextAndNonce: Uint8Array, key: Uint8Array): Uint8Array {\n // Create buffers of nonce and ciphertext.\n const nonce = ciphertextAndNonce.slice(0, ALGORITHM_NONCE_SIZE);\n const ciphertext = ciphertextAndNonce.slice(\n ALGORITHM_NONCE_SIZE,\n ciphertextAndNonce.length,\n );\n\n // Decrypt and return result.\n return gcm(key, nonce).decrypt(ciphertext);\n }\n\n async #getOrGenerateScryptKey(\n password: string,\n o: EncryptedPayload['o'],\n salt?: Uint8Array,\n nativeScryptCrypto?: NativeScrypt,\n ) {\n const hashedPassword = createSHA256Hash(password);\n\n // Check if we already have the key cached\n const cachedKey = salt\n ? getCachedKeyBySalt(hashedPassword, salt)\n : getCachedKeyGeneratedWithSharedSalt(hashedPassword);\n\n if (cachedKey) {\n return {\n key: cachedKey.key,\n salt: cachedKey.salt,\n };\n }\n\n // Create a unique cache key for this KDF operation\n const newSalt = salt ?? SHARED_SALT;\n const cacheKey = this.#createKdfCacheKey(\n hashedPassword,\n o,\n newSalt,\n nativeScryptCrypto,\n );\n\n // Check if there's already an ongoing KDF operation with the same parameters\n const existingPromise = this.#kdfPromiseCache.get(cacheKey);\n if (existingPromise) {\n return existingPromise;\n }\n\n // Limit cache size to prevent unbounded growth\n if (this.#kdfPromiseCache.size >= MAX_KDF_PROMISE_CACHE_SIZE) {\n // Remove the oldest entry (first inserted)\n const firstKey = this.#kdfPromiseCache.keys().next().value;\n if (firstKey) {\n this.#kdfPromiseCache.delete(firstKey);\n }\n }\n\n // Create and cache the promise for the KDF operation\n const kdfPromise = this.#performKdfOperation(\n password,\n o,\n newSalt,\n hashedPassword,\n nativeScryptCrypto,\n );\n\n // Cache the promise and set up cleanup\n this.#kdfPromiseCache.set(cacheKey, kdfPromise);\n\n // Clean up the cache after completion (both success and failure)\n // eslint-disable-next-line no-void\n void kdfPromise.finally(() => {\n this.#kdfPromiseCache.delete(cacheKey);\n });\n\n return kdfPromise;\n }\n\n #createKdfCacheKey(\n hashedPassword: string,\n o: EncryptedPayload['o'],\n salt: Uint8Array,\n nativeScryptCrypto?: NativeScrypt,\n ): string {\n const saltStr = byteArrayToBase64(salt);\n const hasNative = Boolean(nativeScryptCrypto);\n return `${hashedPassword}:${o.N}:${o.r}:${o.p}:${o.dkLen}:${saltStr}:${hasNative}`;\n }\n\n async #performKdfOperation(\n password: string,\n o: EncryptedPayload['o'],\n salt: Uint8Array,\n hashedPassword: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<{ key: Uint8Array; salt: Uint8Array }> {\n let newKey: Uint8Array;\n\n if (nativeScryptCrypto) {\n newKey = await nativeScryptCrypto(\n stringToByteArray(password),\n salt,\n o.N,\n o.r,\n o.p,\n o.dkLen,\n );\n } else {\n newKey = await scryptAsync(password, salt, {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n });\n }\n\n setCachedKey(hashedPassword, salt, newKey);\n\n return {\n key: newKey,\n salt,\n };\n }\n}\n\nconst encryption = new EncryptorDecryptor();\nexport default encryption;\n\n/**\n * Receive a SHA256 hash from a given string\n *\n * @param data - input\n * @returns sha256 hash\n */\nexport function createSHA256Hash(data: string): string {\n const hashedData = sha256(data);\n return bytesToHex(hashedData);\n}\n"]}
1
+ {"version":3,"file":"encryption.js","sourceRoot":"","sources":["../../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N,MAAM,GAAG,CAAC,MAAM,WAAW,CAAC,QAAQ,EAAE,IAAI,EAAE;gBAC1C,CAAC,EAAE,CAAC,CAAC,CAAC;gBACN,CAAC,EAAE,CAAC,CAAC,CAAC;gBACN,CAAC,EAAE,CAAC,CAAC,CAAC;gBACN,KAAK,EAAE,CAAC,CAAC,KAAK;aACf,CAAC,CAA4B,CAAC;QACjC,CAAC;QAED,YAAY,CAAC,cAAc,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;QAE3C,OAAO;YACL,GAAG,EAAE,MAAM;YACX,IAAI;SACL,CAAC;IACJ,CAAC;CACF;AAED,MAAM,UAAU,GAAG,IAAI,kBAAkB,EAAE,CAAC;AAC5C,eAAe,UAAU,CAAC;AAE1B;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAAC,IAAY;IAC3C,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IAChC,OAAO,QAAQ,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["import { decrypt, encrypt, IV_LENGTH } from '@metamask/cryptography/aes-gcm';\nimport {\n getErrorMessage,\n stringToBytes,\n bytesToHex,\n concatBytes,\n remove0x,\n} from '@metamask/utils';\nimport { scryptAsync } from '@noble/hashes/scrypt';\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport type { NativeScrypt } from '../types/encryption.js';\nimport {\n getCachedKeyBySalt,\n getCachedKeyGeneratedWithSharedSalt,\n setCachedKey,\n} from './cache.js';\nimport {\n ALGORITHM_KEY_SIZE,\n MAX_KDF_PROMISE_CACHE_SIZE,\n SCRYPT_N,\n SCRYPT_p,\n SCRYPT_r,\n SCRYPT_SALT_SIZE,\n SHARED_SALT,\n} from './constants.js';\nimport {\n base64ToByteArray,\n byteArrayToBase64,\n bytesToUtf8,\n stringToByteArray,\n} from './utils.js';\n\nexport type EncryptedPayload = {\n // version\n v: '1';\n\n // key derivation function algorithm - scrypt\n t: 'scrypt';\n\n // data\n d: string;\n\n // encryption options - scrypt\n o: {\n N: number;\n r: number;\n p: number;\n dkLen: number;\n };\n\n // Salt options\n saltLen: number;\n};\n\nclass EncryptorDecryptor {\n // Promise cache for ongoing KDF operations to prevent duplicate work\n readonly #kdfPromiseCache = new Map<\n string,\n Promise<{ key: Uint8Array<ArrayBuffer>; salt: Uint8Array<ArrayBuffer> }>\n >();\n\n async encryptString(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n return await this.#encryptStringV1(\n plaintext,\n password,\n nativeScryptCrypto,\n );\n } catch (e) {\n throw new Error(`Unable to encrypt string - ${getErrorMessage(e)}`);\n }\n }\n\n async decryptString(\n encryptedDataStr: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n return await this.#decryptStringV1(\n encryptedData,\n password,\n nativeScryptCrypto,\n );\n }\n }\n throw new Error(\n `Unsupported encrypted data payload - ${encryptedDataStr}`,\n );\n } catch (e) {\n throw new Error(`Unable to decrypt string - ${getErrorMessage(e)}`);\n }\n }\n\n async #encryptStringV1(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n const { key, salt } = await this.#getOrGenerateScryptKey(\n password,\n {\n N: SCRYPT_N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n },\n undefined,\n nativeScryptCrypto,\n );\n\n // Encrypt and prepend salt.\n const plaintextRaw = stringToBytes(plaintext);\n const ciphertextAndNonceAndSalt = concatBytes([\n salt,\n await this.#encrypt(plaintextRaw, key),\n ]);\n\n // Convert to Base64\n const encryptedData = byteArrayToBase64(ciphertextAndNonceAndSalt);\n\n const encryptedPayload: EncryptedPayload = {\n v: '1',\n t: 'scrypt',\n d: encryptedData,\n o: {\n N: SCRYPT_N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n },\n saltLen: SCRYPT_SALT_SIZE,\n };\n\n return JSON.stringify(encryptedPayload);\n }\n\n async #decryptStringV1(\n data: EncryptedPayload,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n const { o, d: base64CiphertextAndNonceAndSalt, saltLen } = data;\n\n // Decode the base64.\n const ciphertextAndNonceAndSalt = base64ToByteArray(\n base64CiphertextAndNonceAndSalt,\n );\n\n // Create buffers of salt and ciphertextAndNonce.\n const salt = ciphertextAndNonceAndSalt.slice(0, saltLen);\n const ciphertextAndNonce = ciphertextAndNonceAndSalt.slice(\n saltLen,\n ciphertextAndNonceAndSalt.length,\n );\n\n // Derive the key.\n const { key } = await this.#getOrGenerateScryptKey(\n password,\n {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n },\n salt,\n nativeScryptCrypto,\n );\n\n // Decrypt and return result.\n return bytesToUtf8(await this.#decrypt(ciphertextAndNonce, key));\n }\n\n getSalt(encryptedDataStr: string) {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n const { d: base64CiphertextAndNonceAndSalt, saltLen } = encryptedData;\n\n // Decode the base64.\n const ciphertextAndNonceAndSalt = base64ToByteArray(\n base64CiphertextAndNonceAndSalt,\n );\n\n // Create buffers of salt and ciphertextAndNonce.\n const salt = ciphertextAndNonceAndSalt.slice(0, saltLen);\n return salt;\n }\n }\n throw new Error(\n `Unsupported encrypted data payload - ${encryptedDataStr}`,\n );\n } catch (e) {\n throw new Error(`Unable to get salt - ${getErrorMessage(e)}`);\n }\n }\n\n getIfEntriesHaveDifferentSalts(entries: string[]): boolean {\n const salts = entries\n .map((e) => {\n try {\n return this.getSalt(e);\n } catch {\n return;\n }\n })\n .filter((s): s is Uint8Array<ArrayBuffer> => s !== undefined);\n\n const strSet = new Set(salts.map((arr) => arr.toString()));\n return strSet.size === salts.length;\n }\n\n async #encrypt(\n plaintext: Uint8Array<ArrayBuffer>,\n key: Uint8Array<ArrayBuffer>,\n ): Promise<Uint8Array<ArrayBuffer>> {\n // Encrypt and prepend nonce.\n const { ciphertext, iv } = await encrypt(key, plaintext);\n\n return concatBytes([iv, ciphertext]);\n }\n\n async #decrypt(\n ciphertextAndNonce: Uint8Array<ArrayBuffer>,\n key: Uint8Array<ArrayBuffer>,\n ): Promise<Uint8Array<ArrayBuffer>> {\n // Create buffers of nonce and ciphertext.\n const nonce = ciphertextAndNonce.slice(0, IV_LENGTH);\n const ciphertext = ciphertextAndNonce.slice(\n IV_LENGTH,\n ciphertextAndNonce.length,\n );\n\n // Decrypt and return result.\n return decrypt(key, nonce, ciphertext);\n }\n\n async #getOrGenerateScryptKey(\n password: string,\n o: EncryptedPayload['o'],\n salt?: Uint8Array<ArrayBuffer>,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<{ key: Uint8Array<ArrayBuffer>; salt: Uint8Array<ArrayBuffer> }> {\n const hashedPassword = createSHA256Hash(password);\n\n // Check if we already have the key cached\n const cachedKey = salt\n ? getCachedKeyBySalt(hashedPassword, salt)\n : getCachedKeyGeneratedWithSharedSalt(hashedPassword);\n\n if (cachedKey) {\n return {\n key: cachedKey.key,\n salt: cachedKey.salt,\n };\n }\n\n // Create a unique cache key for this KDF operation\n const newSalt = salt ?? SHARED_SALT;\n const cacheKey = this.#createKdfCacheKey(\n hashedPassword,\n o,\n newSalt,\n nativeScryptCrypto,\n );\n\n // Check if there's already an ongoing KDF operation with the same parameters\n const existingPromise = this.#kdfPromiseCache.get(cacheKey);\n if (existingPromise) {\n return existingPromise;\n }\n\n // Limit cache size to prevent unbounded growth\n if (this.#kdfPromiseCache.size >= MAX_KDF_PROMISE_CACHE_SIZE) {\n // Remove the oldest entry (first inserted)\n const firstKey = this.#kdfPromiseCache.keys().next().value;\n if (firstKey) {\n this.#kdfPromiseCache.delete(firstKey);\n }\n }\n\n // Create and cache the promise for the KDF operation\n const kdfPromise = this.#performKdfOperation(\n password,\n o,\n newSalt,\n hashedPassword,\n nativeScryptCrypto,\n );\n\n // Cache the promise and set up cleanup\n this.#kdfPromiseCache.set(cacheKey, kdfPromise);\n\n // Clean up the cache after completion (both success and failure)\n // eslint-disable-next-line no-void\n void kdfPromise.finally(() => {\n this.#kdfPromiseCache.delete(cacheKey);\n });\n\n return kdfPromise;\n }\n\n #createKdfCacheKey(\n hashedPassword: string,\n o: EncryptedPayload['o'],\n salt: Uint8Array,\n nativeScryptCrypto?: NativeScrypt,\n ): string {\n const saltStr = byteArrayToBase64(salt);\n const hasNative = Boolean(nativeScryptCrypto);\n return `${hashedPassword}:${o.N}:${o.r}:${o.p}:${o.dkLen}:${saltStr}:${hasNative}`;\n }\n\n async #performKdfOperation(\n password: string,\n o: EncryptedPayload['o'],\n salt: Uint8Array<ArrayBuffer>,\n hashedPassword: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<{ key: Uint8Array<ArrayBuffer>; salt: Uint8Array<ArrayBuffer> }> {\n let newKey: Uint8Array<ArrayBuffer>;\n\n if (nativeScryptCrypto) {\n newKey = await nativeScryptCrypto(\n stringToByteArray(password),\n salt,\n o.N,\n o.r,\n o.p,\n o.dkLen,\n );\n } else {\n newKey = (await scryptAsync(password, salt, {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n })) as Uint8Array<ArrayBuffer>;\n }\n\n setCachedKey(hashedPassword, salt, newKey);\n\n return {\n key: newKey,\n salt,\n };\n }\n}\n\nconst encryption = new EncryptorDecryptor();\nexport default encryption;\n\n/**\n * Receive a SHA256 hash from a given string\n *\n * @param data - input\n * @returns sha256 hash\n */\nexport function createSHA256Hash(data: string): string {\n const hashedData = sha256(data);\n return remove0x(bytesToHex(hashedData));\n}\n"]}
@@ -1,2 +1,2 @@
1
- export declare type NativeScrypt = (passwd: Uint8Array, salt: Uint8Array, N: number, r: number, p: number, size: number) => Promise<Uint8Array>;
1
+ export declare type NativeScrypt = (passwd: Uint8Array, salt: Uint8Array, N: number, r: number, p: number, size: number) => Promise<Uint8Array<ArrayBuffer>>;
2
2
  //# sourceMappingURL=encryption.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"encryption.d.ts","sourceRoot":"","sources":["../../../src/shared/types/encryption.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,OAAO,MAAM,YAAY,GAAG,CACjC,MAAM,EAAE,UAAU,EAClB,IAAI,EAAE,UAAU,EAChB,CAAC,EAAE,MAAM,EACT,CAAC,EAAE,MAAM,EACT,CAAC,EAAE,MAAM,EACT,IAAI,EAAE,MAAM,KACT,OAAO,CAAC,UAAU,CAAC,CAAC"}
1
+ {"version":3,"file":"encryption.d.ts","sourceRoot":"","sources":["../../../src/shared/types/encryption.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,OAAO,MAAM,YAAY,GAAG,CACjC,MAAM,EAAE,UAAU,EAClB,IAAI,EAAE,UAAU,EAChB,CAAC,EAAE,MAAM,EACT,CAAC,EAAE,MAAM,EACT,CAAC,EAAE,MAAM,EACT,IAAI,EAAE,MAAM,KACT,OAAO,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"encryption.js","sourceRoot":"","sources":["../../../src/shared/types/encryption.ts"],"names":[],"mappings":"","sourcesContent":["export declare type NativeScrypt = (\n passwd: Uint8Array,\n salt: Uint8Array,\n N: number,\n r: number,\n p: number,\n size: number,\n) => Promise<Uint8Array>;\n"]}
1
+ {"version":3,"file":"encryption.js","sourceRoot":"","sources":["../../../src/shared/types/encryption.ts"],"names":[],"mappings":"","sourcesContent":["export declare type NativeScrypt = (\n passwd: Uint8Array,\n salt: Uint8Array,\n N: number,\n r: number,\n p: number,\n size: number,\n) => Promise<Uint8Array<ArrayBuffer>>;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/profile-sync-controller",
3
- "version": "33.0.0-preview-0f8c056e2",
3
+ "version": "33.0.0-preview-c2be02bd4",
4
4
  "description": "The profile sync helps developers synchronize data across multiple clients and devices in a privacy-preserving way. All data saved in the user storage database is encrypted client-side to preserve privacy. The user storage provides a modular design, giving developers the flexibility to construct and manage their storage spaces in a way that best suits their needs",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -62,10 +62,10 @@
62
62
  "build:only-clean": "rimraf './dist' './tsconfig.build.tsbuildinfo'",
63
63
  "changelog:update": "../../scripts/update-changelog.sh @metamask/profile-sync-controller",
64
64
  "changelog:validate": "../../scripts/validate-changelog.sh @metamask/profile-sync-controller",
65
- "lint:tsconfigs": "tsx ../../scripts/lint-tsconfigs/lint-tsconfigs.ts",
66
- "lint:tsconfigs:fix": "tsx ../../scripts/lint-tsconfigs/lint-tsconfigs.ts --fix",
67
- "messenger-action-types:check": "tsx ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --esm --check",
68
- "messenger-action-types:generate": "tsx ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --esm --generate",
65
+ "lint:tsconfigs": "node --import ../../scripts/resolver/register.ts --experimental-transform-types ../../scripts/lint-tsconfigs/lint-tsconfigs.ts",
66
+ "lint:tsconfigs:fix": "node --import ../../scripts/resolver/register.ts --experimental-transform-types ../../scripts/lint-tsconfigs/lint-tsconfigs.ts --fix",
67
+ "messenger-action-types:check": "node --import ../../scripts/resolver/register.ts --experimental-transform-types ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --esm --check",
68
+ "messenger-action-types:generate": "node --import ../../scripts/resolver/register.ts --experimental-transform-types ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --esm --generate",
69
69
  "since-latest-release": "../../scripts/since-latest-release.sh",
70
70
  "test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter",
71
71
  "test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache",
@@ -76,13 +76,13 @@
76
76
  "@metamask/address-book-controller": "^8.0.0",
77
77
  "@metamask/base-controller": "^10.0.0",
78
78
  "@metamask/controller-utils": "^13.0.0",
79
+ "@metamask/cryptography": "^1.1.0",
79
80
  "@metamask/key-tree": "^10.1.1",
80
81
  "@metamask/keyring-controller": "^28.1.0",
81
82
  "@metamask/messenger": "^3.0.0",
82
83
  "@metamask/seedless-onboarding-controller": "^11.0.1",
83
84
  "@metamask/superstruct": "^3.4.1",
84
85
  "@metamask/utils": "^12.0.0",
85
- "@noble/ciphers": "^1.3.0",
86
86
  "@noble/curves": "^1.9.2",
87
87
  "@noble/hashes": "^1.8.0",
88
88
  "@signinwithethereum/siwe": "^4.2.1",
@@ -107,7 +107,6 @@
107
107
  "nock": "^13.5.6",
108
108
  "rimraf": "^6.1.3",
109
109
  "ts-jest": "^29.4.14",
110
- "tsx": "^4.23.15",
111
110
  "typedoc": "^0.25.13",
112
111
  "typedoc-plugin-missing-exports": "^2.0.0",
113
112
  "typescript": "npm:@typescript/typescript6@^6.0.2",