@metamask-previews/profile-sync-controller 32.2.0-preview-f61294996 → 32.2.0-preview-8b8e439a2

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
@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
13
13
  - `beginMfaEnrollment` accepts an `accessToken` option so enrollment can begin with an elevated token
14
14
  - `AuthenticationController.beginCredentialEnrollment` sends the elevated token while a step-up session is live, since enrolling additional credentials requires AAL2
15
15
  - Add the `email_socially_verified`, `multi_primary_srp` and `aal2_required` MFA error codes, a `StepUpRequiredError` class, and support for the `retry_after_seconds` error field when computing `retryAfterMs`
16
+ - Add `pairedIdentifierIds` to `UserProfile` in `srpSessionData`, set from the login response and, on the primary SRP session, from the SRP and social pairing responses, so clients can tell whether a profile has been socially paired ([#10394](https://github.com/MetaMask/core/pull/10394))
16
17
 
17
18
  ### Changed
18
19
 
@@ -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,EAC3C,MAAM,0CAA0C,CAAC;AAYlD,OAAO,KAAK,EAEV,aAAa,EACb,YAAY,EAGZ,WAAW,EACX,kBAAkB,EAClB,iBAAiB,EACjB,eAAe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ationController.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,kBAAkB,EAClB,qBAAqB,EACrB,oBAAoB,EACpB,uBAAuB,EACvB,eAAe,EAChB,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;IACH,mBAAmB,CAAC,EAAE,kBAAkB,EAAE,CAAC;IAC3C;;;OAGG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC;;;;;;;;;;OAUG;IACH,mBAAmB,CAAC,EA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;;;;;;;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"}
@@ -34,7 +34,7 @@ const metadata = {
34
34
  usedInUi: true,
35
35
  },
36
36
  srpSessionData: {
37
- // Remove access token from state logs
37
+ // Remove access token and paired identifiers from state logs
38
38
  includeInStateLogs: (srpSessionData) => {
39
39
  // Unreachable branch, included just to fix a type error for the case where this property is
40
40
  // unset. The type gets collapsed to include `| undefined` even though `undefined` is never
@@ -46,9 +46,11 @@ const metadata = {
46
46
  }
47
47
  return Object.entries(srpSessionData).reduce((sanitizedSrpSessionData, [key, value]) => {
48
48
  const { accessToken: _unused, ...tokenWithoutAccessToken } = value.token;
49
+ const { pairedIdentifierIds: _unusedPairedIdentifierIds, ...profileWithoutPairedIdentifierIds } = value.profile;
49
50
  sanitizedSrpSessionData[key] = {
50
51
  ...value,
51
52
  token: tokenWithoutAccessToken,
53
+ profile: profileWithoutPairedIdentifierIds,
52
54
  };
53
55
  return sanitizedSrpSessionData;
54
56
  }, {});
@@ -200,11 +202,16 @@ export class AuthenticationController extends BaseController {
200
202
  if (!state.srpSessionData) {
201
203
  state.srpSessionData = {};
202
204
  }
205
+ // The API omits `paired_identifier_ids` when it fails to load them, so
206
+ // keep the last known value rather than wiping it.
207
+ const pairedIdentifierIds = loginResponse.profile.pairedIdentifierIds ??
208
+ state.srpSessionData[resolvedId]?.profile.pairedIdentifierIds;
203
209
  state.srpSessionData[resolvedId] = {
204
210
  ...loginResponse,
205
211
  profile: {
206
212
  ...loginResponse.profile,
207
213
  metaMetricsId,
214
+ ...(pairedIdentifierIds ? { pairedIdentifierIds } : {}),
208
215
  },
209
216
  };
210
217
  });
@@ -430,11 +437,12 @@ export class AuthenticationController extends BaseController {
430
437
  return;
431
438
  }
432
439
  try {
433
- await this.#auth.pairSocialIdentifier({
440
+ const pairedIdentifierIds = await this.#auth.pairSocialIdentifier({
434
441
  identifierType,
435
442
  socialJwt,
436
443
  ...(email ? { email } : {}),
437
444
  }, primaryAccessToken);
445
+ this.#setPrimaryPairedIdentifierIds(pairedIdentifierIds);
438
446
  this.#clearNeedsSocialPairing();
439
447
  }
440
448
  catch (error) {
@@ -518,10 +526,29 @@ export class AuthenticationController extends BaseController {
518
526
  return [];
519
527
  }
520
528
  const primaryAccessToken = accessTokens[0]; // Associated with primary SRP.
521
- const { profileAliases, profile: { canonicalProfileId }, } = await this.#auth.pairSrpProfiles(accessTokens, primaryAccessToken);
529
+ const { profileAliases, profile: { canonicalProfileId, pairedIdentifierIds }, } = await this.#auth.pairSrpProfiles(accessTokens, primaryAccessToken);
522
530
  this.#propagateCanonical(canonicalProfileId);
531
+ this.#setPrimaryPairedIdentifierIds(pairedIdentifierIds);
523
532
  return profileAliases;
524
533
  }
534
+ /**
535
+ * Pair calls use the primary SRP's token, so their response only describes
536
+ * the primary's profile: secondaries skipped by the server are not in it.
537
+ *
538
+ * @param pairedIdentifierIds - Identifiers returned by the pair call, if any.
539
+ */
540
+ #setPrimaryPairedIdentifierIds(pairedIdentifierIds) {
541
+ if (!pairedIdentifierIds) {
542
+ return;
543
+ }
544
+ const primaryEntropySourceId = this.#getPrimaryEntropySourceId();
545
+ this.update((state) => {
546
+ const entry = state.srpSessionData?.[primaryEntropySourceId];
547
+ if (entry?.profile) {
548
+ entry.profile.pairedIdentifierIds = pairedIdentifierIds;
549
+ }
550
+ });
551
+ }
525
552
  #propagateCanonical(canonicalProfileId) {
526
553
  const { srpSessionData } = this.state;
527
554
  if (!srpSessionData) {
@@ -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,wBAAwB,EACxB,2BAA2B,EAC3B,6BAA6B,EAC7B,wBAAwB,GACzB,MAAM,oDAAoD,CAAC;AAqB5D,OAAO,EACL,+BAA+B,EAC/B,QAAQ,EACR,GAAG,EACH,aAAa,EACb,iBAAiB,EACjB,eAAe,EACf,yBAAyB,GAC1B,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;AA2ClD,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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,CAAC,CAAC;QACxC,MAAM,IAAI,GAAG,MAAM,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 BeginStepUpRequestStruct,\n CompleteStepUpRequestStruct,\n GetElevatedTokenRequestStruct,\n parseElevatedTokenClaims,\n} from '../../sdk/authentication-jwt-bearer/mfa/schemas.js';\nimport type {\n LoginIdentifierType,\n LoginResponse,\n ProfileAlias,\n SRPInterface,\n SrpLoginTag,\n UserProfile,\n UserProfileLineage,\n OidcTokenAudience,\n OidcTokenClaims,\n BeginEnrollmentRequest,\n CompleteEnrollmentRequest,\n EnrolledCredential,\n EnrollmentChallenge,\n BeginStepUpRequest,\n CompleteStepUpRequest,\n ElevatedProfileToken,\n GetElevatedTokenRequest,\n StepUpChallenge,\n} from '../../sdk/index.js';\nimport {\n assertMessageStartsWithMetamask,\n AuthType,\n Env,\n JwtBearerAuth,\n PairConflictError,\n getMfaErrorCode,\n ElevatedTokenInvalidError,\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 * Epoch-ms hard expiry of the in-memory elevated session, or undefined when\n * none is open. Lets UI show \"verified\" state without holding the token.\n */\n stepUpSessionExpiresAt?: number;\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 from state logs\n includeInStateLogs: (srpSessionData) => {\n // Unreachable branch, included just to fix a type error for the case where this property is\n // unset. The type gets collapsed to include `| undefined` even though `undefined` is never\n // set here, because we don't yet use `exactOptionalPropertyTypes`.\n // TODO: Remove branch after enabling `exactOptionalPropertyTypes`\n // ref: https://github.com/MetaMask/core/issues/6565\n if (srpSessionData === null || srpSessionData === undefined) {\n return null;\n }\n return Object.entries(srpSessionData).reduce<Record<string, Json>>(\n (sanitizedSrpSessionData, [key, value]) => {\n const { accessToken: _unused, ...tokenWithoutAccessToken } =\n value.token;\n sanitizedSrpSessionData[key] = {\n ...value,\n token: tokenWithoutAccessToken,\n };\n return sanitizedSrpSessionData;\n },\n {},\n );\n },\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n 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 stepUpSessionExpiresAt: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\n/**\n * Lifetime of an elevated session. Deliberately shorter than the\n * elevated token's own `exp` so a fresh ceremony is required per sensitive\n * action window, per the MFA phase-1 specification.\n */\nexport const STEP_UP_SESSION_TTL_MS = 60_000;\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 'beginStepUp',\n 'completeStepUp',\n 'getElevatedProfileToken',\n 'clearStepUpSession',\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 #stepUpSession: {\n token: ElevatedProfileToken;\n expiresAt: number;\n } | null = null;\n\n #stepUpTimer: ReturnType<typeof setTimeout> | undefined;\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.clearStepUpSession();\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 state.srpSessionData[resolvedId] = {\n ...loginResponse,\n profile: {\n ...loginResponse.profile,\n metaMetricsId,\n },\n };\n });\n }\n\n #assertIsUnlocked(methodName: string): void {\n if (!this.#isUnlocked) {\n throw new Error(`${methodName} - unable to proceed, wallet is locked`);\n }\n }\n\n #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 await this.#auth.pairSocialIdentifier(\n {\n identifierType,\n socialJwt,\n ...(email ? { email } : {}),\n },\n primaryAccessToken,\n );\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 },\n } = await this.#auth.pairSrpProfiles(accessTokens, primaryAccessToken);\n this.#propagateCanonical(canonicalProfileId);\n return profileAliases;\n }\n\n #propagateCanonical(canonicalProfileId: string): void {\n const { srpSessionData } = this.state;\n if (!srpSessionData) {\n return;\n }\n\n this.update((state) => {\n for (const entry of Object.values(state.srpSessionData ?? {})) {\n if (entry?.profile) {\n entry.profile.canonicalProfileId = canonicalProfileId;\n }\n }\n });\n }\n\n /**\n * Returns the canonical profile id from the primary SRP's cached session.\n * Returns `null` when no session exists yet for the primary SRP.\n *\n * Always reads from the primary SRP because the canonical is shared across\n * all paired SRPs after `#propagateCanonical`.\n *\n * @returns The canonical profile id, or `null` if unavailable.\n */\n #getCanonicalProfileId(): string | null {\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n return (\n this.state.srpSessionData?.[primaryEntropySourceId]?.profile\n ?.canonicalProfileId ?? null\n );\n }\n\n /**\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 // An elevated session must not outlive a rejected base session.\n this.clearStepUpSession();\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 // Enrolling beyond the first credential requires AAL2: send the elevated\n // token while a session is live and let the server decide.\n const accessToken = this.getElevatedProfileToken()?.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 // The factor set changed: require a fresh ceremony against the new set.\n this.clearStepUpSession();\n\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 step-up 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 beginStepUp(\n request: BeginStepUpRequest,\n ): Promise<StepUpChallenge> {\n this.#assertIsUnlocked('beginStepUp');\n const sessionEpoch = this.#authSessionEpoch;\n assertValidMfaRequest(request, BeginStepUpRequestStruct);\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n const challenge = await this.#runMfaRequest(\n 'MFA Step-Up 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, 'beginStepUp');\n return challenge;\n }\n\n /**\n * Completes step-up verification and opens a short-lived elevated session.\n *\n * The AAL2 assertion returned by the MFA service is exchanged at Hydra for\n * an elevated access token, whose claims are checked before the session\n * opens. The token itself never enters controller state.\n *\n * @param request - Flow identifier, platform or email proof, and trace reason.\n * @returns The elevated profile access token.\n */\n public async completeStepUp(\n request: CompleteStepUpRequest,\n ): Promise<ElevatedProfileToken> {\n this.#assertIsUnlocked('completeStepUp');\n const sessionEpoch = this.#authSessionEpoch;\n assertValidMfaRequest(request, CompleteStepUpRequestStruct);\n const { type } = request.proof;\n const { operation } = request.reason;\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n const assertion = await this.#runMfaRequest(\n 'MFA Step-Up 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(sessionEpoch, 'completeStepUp');\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(sessionEpoch, 'completeStepUp');\n\n let decodedClaims: unknown;\n try {\n decodedClaims = decodeJwtPayload(accessToken.accessToken);\n } catch (error) {\n throw new ElevatedTokenInvalidError(toErrorMessage(error));\n }\n const claims = parseElevatedTokenClaims(decodedClaims);\n if (claims.exp * 1000 <= Date.now()) {\n throw new ElevatedTokenInvalidError('Elevated token is expired');\n }\n\n const token: ElevatedProfileToken = { ...accessToken, claims };\n this.#openStepUpSession(token);\n return token;\n }\n\n /**\n * Returns the active elevated token when it meets the requested 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 elevated token, or null when no reusable session exists.\n */\n public getElevatedProfileToken(\n request: GetElevatedTokenRequest = {},\n ): ElevatedProfileToken | null {\n this.#assertIsUnlocked('getElevatedProfileToken');\n assertValidMfaRequest(request, GetElevatedTokenRequestStruct);\n const session = this.#stepUpSession;\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.clearStepUpSession();\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 elevated 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 elevated token.\n */\n #openStepUpSession(token: ElevatedProfileToken): void {\n this.clearStepUpSession();\n const expiresAt = Math.min(\n token.obtainedAt + STEP_UP_SESSION_TTL_MS,\n token.claims.exp * 1000,\n );\n this.#stepUpSession = { token, expiresAt };\n this.update((state) => {\n state.stepUpSessionExpiresAt = expiresAt;\n });\n this.#stepUpTimer = setTimeout(\n () => this.clearStepUpSession(),\n Math.max(0, expiresAt - Date.now()),\n );\n // Never keep a Node process alive for the expiry timer (tests, tooling).\n (this.#stepUpTimer as { unref?: () => void }).unref?.();\n }\n\n /**\n * Clears the in-memory elevated session and its expiration timer.\n */\n public clearStepUpSession(): void {\n if (this.#stepUpTimer !== undefined) {\n clearTimeout(this.#stepUpTimer);\n this.#stepUpTimer = undefined;\n }\n this.#stepUpSession = null;\n if (this.state.stepUpSessionExpiresAt !== undefined) {\n this.update((state) => {\n state.stepUpSessionExpiresAt = undefined;\n });\n }\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.clearStepUpSession();\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.clearStepUpSession();\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,wBAAwB,EACxB,2BAA2B,EAC3B,6BAA6B,EAC7B,wBAAwB,GACzB,MAAM,oDAAoD,CAAC;AAsB5D,OAAO,EACL,+BAA+B,EAC/B,QAAQ,EACR,GAAG,EACH,aAAa,EACb,iBAAiB,EACjB,eAAe,EACf,yBAAyB,GAC1B,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;AA2ClD,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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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 BeginStepUpRequestStruct,\n CompleteStepUpRequestStruct,\n GetElevatedTokenRequestStruct,\n parseElevatedTokenClaims,\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 BeginStepUpRequest,\n CompleteStepUpRequest,\n ElevatedProfileToken,\n GetElevatedTokenRequest,\n StepUpChallenge,\n} from '../../sdk/index.js';\nimport {\n assertMessageStartsWithMetamask,\n AuthType,\n Env,\n JwtBearerAuth,\n PairConflictError,\n getMfaErrorCode,\n ElevatedTokenInvalidError,\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 * Epoch-ms hard expiry of the in-memory elevated session, or undefined when\n * none is open. Lets UI show \"verified\" state without holding the token.\n */\n stepUpSessionExpiresAt?: number;\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 stepUpSessionExpiresAt: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\n/**\n * Lifetime of an elevated session. Deliberately shorter than the\n * elevated token's own `exp` so a fresh ceremony is required per sensitive\n * action window, per the MFA phase-1 specification.\n */\nexport const STEP_UP_SESSION_TTL_MS = 60_000;\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 'beginStepUp',\n 'completeStepUp',\n 'getElevatedProfileToken',\n 'clearStepUpSession',\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 #stepUpSession: {\n token: ElevatedProfileToken;\n expiresAt: number;\n } | null = null;\n\n #stepUpTimer: ReturnType<typeof setTimeout> | undefined;\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.clearStepUpSession();\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 // An elevated session must not outlive a rejected base session.\n this.clearStepUpSession();\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 // Enrolling beyond the first credential requires AAL2: send the elevated\n // token while a session is live and let the server decide.\n const accessToken = this.getElevatedProfileToken()?.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 // The factor set changed: require a fresh ceremony against the new set.\n this.clearStepUpSession();\n\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 step-up 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 beginStepUp(\n request: BeginStepUpRequest,\n ): Promise<StepUpChallenge> {\n this.#assertIsUnlocked('beginStepUp');\n const sessionEpoch = this.#authSessionEpoch;\n assertValidMfaRequest(request, BeginStepUpRequestStruct);\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n const challenge = await this.#runMfaRequest(\n 'MFA Step-Up 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, 'beginStepUp');\n return challenge;\n }\n\n /**\n * Completes step-up verification and opens a short-lived elevated session.\n *\n * The AAL2 assertion returned by the MFA service is exchanged at Hydra for\n * an elevated access token, whose claims are checked before the session\n * opens. The token itself never enters controller state.\n *\n * @param request - Flow identifier, platform or email proof, and trace reason.\n * @returns The elevated profile access token.\n */\n public async completeStepUp(\n request: CompleteStepUpRequest,\n ): Promise<ElevatedProfileToken> {\n this.#assertIsUnlocked('completeStepUp');\n const sessionEpoch = this.#authSessionEpoch;\n assertValidMfaRequest(request, CompleteStepUpRequestStruct);\n const { type } = request.proof;\n const { operation } = request.reason;\n const primaryEntropySourceId = this.#getPrimaryEntropySourceId();\n const assertion = await this.#runMfaRequest(\n 'MFA Step-Up 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(sessionEpoch, 'completeStepUp');\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(sessionEpoch, 'completeStepUp');\n\n let decodedClaims: unknown;\n try {\n decodedClaims = decodeJwtPayload(accessToken.accessToken);\n } catch (error) {\n throw new ElevatedTokenInvalidError(toErrorMessage(error));\n }\n const claims = parseElevatedTokenClaims(decodedClaims);\n if (claims.exp * 1000 <= Date.now()) {\n throw new ElevatedTokenInvalidError('Elevated token is expired');\n }\n\n const token: ElevatedProfileToken = { ...accessToken, claims };\n this.#openStepUpSession(token);\n return token;\n }\n\n /**\n * Returns the active elevated token when it meets the requested 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 elevated token, or null when no reusable session exists.\n */\n public getElevatedProfileToken(\n request: GetElevatedTokenRequest = {},\n ): ElevatedProfileToken | null {\n this.#assertIsUnlocked('getElevatedProfileToken');\n assertValidMfaRequest(request, GetElevatedTokenRequestStruct);\n const session = this.#stepUpSession;\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.clearStepUpSession();\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 elevated 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 elevated token.\n */\n #openStepUpSession(token: ElevatedProfileToken): void {\n this.clearStepUpSession();\n const expiresAt = Math.min(\n token.obtainedAt + STEP_UP_SESSION_TTL_MS,\n token.claims.exp * 1000,\n );\n this.#stepUpSession = { token, expiresAt };\n this.update((state) => {\n state.stepUpSessionExpiresAt = expiresAt;\n });\n this.#stepUpTimer = setTimeout(\n () => this.clearStepUpSession(),\n Math.max(0, expiresAt - Date.now()),\n );\n // Never keep a Node process alive for the expiry timer (tests, tooling).\n (this.#stepUpTimer as { unref?: () => void }).unref?.();\n }\n\n /**\n * Clears the in-memory elevated session and its expiration timer.\n */\n public clearStepUpSession(): void {\n if (this.#stepUpTimer !== undefined) {\n clearTimeout(this.#stepUpTimer);\n this.#stepUpTimer = undefined;\n }\n this.#stepUpSession = null;\n if (this.state.stepUpSessionExpiresAt !== undefined) {\n this.update((state) => {\n state.stepUpSessionExpiresAt = undefined;\n });\n }\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.clearStepUpSession();\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.clearStepUpSession();\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"]}
@@ -3,7 +3,7 @@ import type { MetaMetricsAuth } from '../../shared/types/services.js';
3
3
  import type { MfaStepUpAssertion } from './mfa/services.js';
4
4
  import type { EnrolledCredential, EnrollmentChallenge, EnrollmentProof, MfaCredentialType, StepUpChallenge, StepUpProof } from './mfa/types.js';
5
5
  import type { PairProfilesResponse } from './services.js';
6
- import type { AuthConfig, AccessToken, AuthSigningOptions, AuthStorageOptions, AuthType, IBaseAuth, LoginIdentifierType, OidcTokenAudience, OidcTokenClaims, PairSocialIdentifierParams, SrpLoginTag, UserProfile, UserProfileLineage } from './types.js';
6
+ import type { AuthConfig, AccessToken, AuthSigningOptions, AuthStorageOptions, AuthType, IBaseAuth, LoginIdentifierType, OidcTokenAudience, OidcTokenClaims, PairSocialIdentifierParams, ProfileIdentifier, SrpLoginTag, UserProfile, UserProfileLineage } from './types.js';
7
7
  type JwtBearerAuth_SRP_Options = {
8
8
  storage: AuthStorageOptions;
9
9
  signing?: AuthSigningOptions;
@@ -94,7 +94,7 @@ export declare class SRPJwtBearerAuth implements IBaseAuth {
94
94
  * @returns Elevated access token.
95
95
  */
96
96
  exchangeMfaAssertion(assertionJwt: string): Promise<AccessToken>;
97
- pairSocialIdentifier(params: PairSocialIdentifierParams, authAccessToken: string): Promise<void>;
97
+ pairSocialIdentifier(params: PairSocialIdentifierParams, authAccessToken: string): Promise<ProfileIdentifier[] | undefined>;
98
98
  pairSrpProfiles(accessTokens: string[], authAccessToken: string): Promise<PairProfilesResponse>;
99
99
  signMessage(message: string, entropySourceId?: string): Promise<string>;
100
100
  isSnapConnected(): Promise<boolean>;
@@ -1 +1 @@
1
- {"version":3,"file":"flow-srp.d.ts","sourceRoot":"","sources":["../../../src/sdk/authentication-jwt-bearer/flow-srp.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAE9C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAiBtE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,KAAK,EACV,kBAAkB,EAClB,mBAAmB,EACnB,eAAe,EACf,iBAAiB,EACjB,eAAe,EACf,WAAW,EACZ,MAAM,gBAAgB,CAAC;AAWxB,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,KAAK,EACV,UAAU,EACV,WAAW,EACX,kBAAkB,EAClB,kBAAkB,EAClB,QAAQ,EACR,SAAS,EACT,mBAAmB,EAEnB,iBAAiB,EACjB,eAAe,EACf,0BAA0B,EAC1B,WAAW,EACX,WAAW,EACX,kBAAkB,EACnB,MAAM,YAAY,CAAC;AAIpB,KAAK,yBAAyB,GAAG;IAC/B,OAAO,EAAE,kBAAkB,CAAC;IAC5B,OAAO,CAAC,EAAE,kBAAkB,CAAC;IAC7B;;;OAGG;IACH,WAAW,CAAC,EAAE,CAAC,eAAe,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,WAAW,CAAC,CAAC;IACjE;;;OAGG;IACH,sBAAsB,CAAC,EAAE,CACvB,eAAe,CAAC,EAAE,MAAM,KACrB,OAAO,CAAC,mBAAmB,CAAC,CAAC;IAClC,cAAc,CAAC,EAAE;QACf,iBAAiB,CAAC,EAAE,MAAM,CAAC;QAC3B,eAAe,CAA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KG;IACG,oBAAoB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAMrE;IAEK,oBAAoB,CACxB,MAAM,EAAE,0BAA0B,EAClC,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,iBAAiB,EAAE,GAAG,SAAS,CAAC,CAM1C;IAEK,eAAe,CACnB,YAAY,EAAE,MAAM,EAAE,EACtB,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,oBAAoB,CAAC,CAqC/B;IAEK,WAAW,CACf,OAAO,EAAE,MAAM,EACf,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,CAAC,CAEjB;IAEK,eAAe,IAAI,OAAO,CAAC,OAAO,CAAC,CASxC;IAEK,WAAW,IAAI,OAAO,CAAC,MAAM,CAAC,CAMnC;CAyKF"}
@@ -216,7 +216,7 @@ export class SRPJwtBearerAuth {
216
216
  return await authorizeOIDC(assertionJwt, this.#config.env, this.#config.platform);
217
217
  }
218
218
  async pairSocialIdentifier(params, authAccessToken) {
219
- await pairSocialIdentifier(params, authAccessToken, this.#config.env);
219
+ return await pairSocialIdentifier(params, authAccessToken, this.#config.env);
220
220
  }
221
221
  async pairSrpProfiles(accessTokens, authAccessToken) {
222
222
  // Order-insensitive key: the same token set in any order maps to the same
@@ -1 +1 @@
1
- {"version":3,"file":"flow-srp.js","sourceRoot":"","sources":["../../../src/sdk/authentication-jwt-bearer/flow-srp.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,MAAM,wCAAwC,CAAC;AACpF,OAAO,EACL,oBAAoB,EACpB,+BAA+B,EAC/B,WAAW,EACX,eAAe,GAChB,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAC5E,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,iBAAiB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C5C,uDAAuD;QACvD,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,CAAC,GAAG,IAAI,CAAC,gBAAgB,EAAE,OAAO,IAAI,CAAC,EAAE,CAAC;YACxE,IAAI,CAAC;gBACH,OAAO,MAAM,IAAI,CAAC,aAAa,CAAC,eAAe,CAAC,CAAC;YACnD,CAAC;YAAC,OAAO,CAAC,EAAE,CAAC;gBACX,wCAAwC;gBACxC,IAAI,CAAC,gBAAgB,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,CAAC;oBAC1C,MAAM,CAAC,CAAC;gBACV,CAAC;gBAED,uCAAuC;gBACvC,IAAI,OAAO,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;oBACrC,MAAM,CAAC,CAAC;gBACV,CAAC;gBAED,2CAA2C;gBAC3C,MAAM,MAAM,GAAG,CAAC,CAAC,YAAY,IAAI,IAAI,CAAC,kBAAkB,CAAC;gBACzD,MAAM,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;gBAE9B,0BAA0B;YAC5B,CAAC;QACH,CAAC;QAED,2EAA2E;QAC3E,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACrE,CAAC;IAED,yBAAyB,CACvB,KAAa,EACb,SAAiB,EACjB,GAAiB;QAIjB,IAAI,GAAG,EAAE,CAAC;YACR,OAAO,YAAY,KAAK,IAAI,SAAS,IAAI,GAAG,EAAW,CAAC;QAC1D,CAAC;QACD,OAAO,YAAY,KAAK,IAAI,SAAS,EAAW,CAAC;IACnD,CAAC;CACF","sourcesContent":["import type { Eip1193Provider } from 'ethers';\n\nimport type { MetaMetricsAuth } from '../../shared/types/services.js';\nimport { MfaError, ValidationError, RateLimitedError } from '../errors.js';\nimport { getMetaMaskProviderEIP6963 } from '../utils/eip-6963-metamask-provider.js';\nimport {\n MESSAGE_SIGNING_SNAP,\n assertMessageStartsWithMetamask,\n connectSnap,\n isSnapConnected,\n} from '../utils/messaging-signing-snap-requests.js';\nimport { validateLoginResponse } from '../utils/validate-login-response.js';\nimport {\n getMfaCredentials,\n mfaEnroll,\n mfaEnrollComplete,\n mfaVerify,\n mfaVerifyComplete,\n} from './mfa/services.js';\nimport type { MfaStepUpAssertion } from './mfa/services.js';\nimport type {\n EnrolledCredential,\n EnrollmentChallenge,\n EnrollmentProof,\n MfaCredentialType,\n StepUpChallenge,\n StepUpProof,\n} from './mfa/types.js';\nimport {\n authenticate,\n authorizeOIDC,\n getCustomerServiceToken,\n getNonce,\n getPartnerIdentityToken,\n getUserProfileLineage,\n pairProfiles,\n pairSocialIdentifier,\n} from './services.js';\nimport type { PairProfilesResponse } from './services.js';\nimport type {\n AuthConfig,\n AccessToken,\n AuthSigningOptions,\n AuthStorageOptions,\n AuthType,\n IBaseAuth,\n LoginIdentifierType,\n LoginResponse,\n OidcTokenAudience,\n OidcTokenClaims,\n PairSocialIdentifierParams,\n SrpLoginTag,\n UserProfile,\n UserProfileLineage,\n} from './types.js';\nimport { computeIdentifierId } from './utils/identifier.js';\nimport * as timeUtils from './utils/time.js';\n\ntype JwtBearerAuth_SRP_Options = {\n storage: AuthStorageOptions;\n signing?: AuthSigningOptions;\n /**\n * Resolves the login tag for a given entropy source.\n * When omitted, `raw_message` stays untagged (`metamask:<nonce>:<pubkey>`).\n */\n getLoginTag?: (entropySourceId?: string) => Promise<SrpLoginTag>;\n /**\n * Resolves the metametrics `identifier_type` for a given entropy source.\n * Defaults to `'SRP'` when omitted.\n */\n getLoginIdentifierType?: (\n entropySourceId?: string,\n ) => Promise<LoginIdentifierType>;\n rateLimitRetry?: {\n cooldownDefaultMs?: number; // default cooldown when 429 has no Retry-After\n maxLoginRetries?: number; // maximum number of login retries on rate limit\n };\n};\n\n// How long a successful pairing result stays cached so identical payloads\n// (concurrent or sequential retries) reuse it instead of re-hitting the endpoint.\nexport const PAIR_DEDUPE_TTL_MS = 30_000;\n\nconst getDefaultEIP6963Provider = async () => {\n const provider = await getMetaMaskProviderEIP6963();\n if (!provider) {\n throw new ValidationError('No MetaMask wallet connected');\n }\n return provider;\n};\n\nconst getDefaultEIP6963SigningOptions = (\n customProvider?: Eip1193Provider,\n): AuthSigningOptions => ({\n getIdentifier: async (entropySourceId?: string): Promise<string> => {\n const provider = customProvider ?? (await getDefaultEIP6963Provider());\n return await MESSAGE_SIGNING_SNAP.getPublicKey(provider, entropySourceId);\n },\n signMessage: async (\n message: string,\n entropySourceId?: string,\n ): Promise<string> => {\n const provider = customProvider ?? (await getDefaultEIP6963Provider());\n assertMessageStartsWithMetamask(message);\n return await MESSAGE_SIGNING_SNAP.signMessage(\n provider,\n message,\n entropySourceId,\n );\n },\n});\n\nexport class SRPJwtBearerAuth implements IBaseAuth {\n readonly #config: AuthConfig;\n\n readonly #options: {\n storage: AuthStorageOptions;\n signing: AuthSigningOptions;\n };\n\n readonly #metametrics?: MetaMetricsAuth;\n\n // Map to store ongoing login promises by entropySourceId\n readonly #ongoingLogins = new Map<\n string | undefined,\n Promise<LoginResponse>\n >();\n\n // Map to dedupe pairing calls by an order-insensitive token-set key.\n // Holds the in-flight promise (coalescing concurrent callers) and keeps it\n // for a short TTL after success (collapsing sequential retries).\n readonly #ongoingPairings = new Map<\n string,\n { promise: Promise<PairProfilesResponse>; expiresAt: number }\n >();\n\n // Default cooldown when 429 has no Retry-After header\n readonly #cooldownDefaultMs: number;\n\n // Maximum number of login retries on rate limit errors\n readonly #maxLoginRetries: number;\n\n readonly #getLoginTag?: (entropySourceId?: string) => Promise<SrpLoginTag>;\n\n readonly #getLoginIdentifierType?: (\n entropySourceId?: string,\n ) => Promise<LoginIdentifierType>;\n\n #customProvider?: Eip1193Provider;\n\n constructor(\n config: AuthConfig & { type: AuthType.SRP },\n options: JwtBearerAuth_SRP_Options & {\n customProvider?: Eip1193Provider;\n metametrics?: MetaMetricsAuth;\n },\n ) {\n this.#config = config;\n this.#customProvider = options.customProvider;\n this.#getLoginTag = options.getLoginTag;\n this.#getLoginIdentifierType = options.getLoginIdentifierType;\n this.#options = {\n storage: options.storage,\n signing:\n options.signing ??\n getDefaultEIP6963SigningOptions(this.#customProvider),\n };\n this.#metametrics = options.metametrics;\n\n // Apply rate limit retry config if provided\n this.#cooldownDefaultMs =\n options.rateLimitRetry?.cooldownDefaultMs ?? 10000;\n this.#maxLoginRetries = options.rateLimitRetry?.maxLoginRetries ?? 1;\n }\n\n setCustomProvider(provider: Eip1193Provider) {\n this.#customProvider = provider;\n this.#options.signing = getDefaultEIP6963SigningOptions(provider);\n }\n\n // TODO: might be easier to keep entropySourceId as a class param and use multiple SRPJwtBearerAuth instances where needed\n async getAccessToken(entropySourceId?: string): Promise<string> {\n const session = await this.#getAuthSession(entropySourceId);\n if (session) {\n return session.token.accessToken;\n }\n\n const loginResponse = await this.#login(entropySourceId);\n return loginResponse.token.accessToken;\n }\n\n async getUserProfile(entropySourceId?: string): Promise<UserProfile> {\n const session = await this.#getAuthSession(entropySourceId);\n if (session) {\n return session.profile;\n }\n\n const loginResponse = await this.#login(entropySourceId);\n return loginResponse.profile;\n }\n\n async getIdentifier(entropySourceId?: string): Promise<string> {\n return await this.#options.signing.getIdentifier(entropySourceId);\n }\n\n async getUserProfileLineage(\n entropySourceId?: string,\n ): Promise<UserProfileLineage> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await getUserProfileLineage(this.#config.env, accessToken);\n }\n\n async getCustomerServiceToken(entropySourceId?: string): Promise<string> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await getCustomerServiceToken(this.#config.env, accessToken);\n }\n\n async getPartnerIdentityToken(\n claims: OidcTokenClaims,\n audience: OidcTokenAudience,\n entropySourceId?: string,\n ): Promise<string> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await getPartnerIdentityToken(\n this.#config.env,\n accessToken,\n claims,\n audience,\n );\n }\n\n /**\n * Begins enrollment of an MFA credential for the primary profile.\n *\n * @param type - Credential type to enroll.\n * @param options - Enrollment options.\n * @param options.email - Email address, required for email OTP.\n * @param options.entropySourceId - Entropy source whose profile owns the\n * credential.\n * @param options.accessToken - Bearer to use instead of the base session\n * token; an elevated token is required once a credential is already enrolled.\n * @returns Enrollment challenge for the client ceremony.\n */\n async beginMfaEnrollment(\n type: MfaCredentialType,\n options?: {\n email?: string;\n entropySourceId?: string;\n accessToken?: string;\n },\n ): Promise<EnrollmentChallenge> {\n const { email, entropySourceId } = options ?? {};\n const accessToken =\n options?.accessToken ?? (await this.getAccessToken(entropySourceId));\n const result = await mfaEnroll(this.#config.env, accessToken, {\n credential_type: type,\n ...(email ? { identifier: email } : {}),\n });\n\n if (type === 'passkey') {\n if (!result.publicKey) {\n throw new MfaError(\n 'invalid_response',\n 'Passkey enrollment response is missing creation data',\n );\n }\n return {\n type,\n flowId: result.flowId,\n expiresAt: result.expiresAt,\n publicKey: result.publicKey,\n };\n }\n return {\n type,\n flowId: result.flowId,\n expiresAt: result.expiresAt,\n };\n }\n\n /**\n * Completes enrollment of an MFA credential.\n *\n * @param flowId - Identifier returned by the begin call.\n * @param proof - Platform attestation or email code.\n * @param entropySourceId - Entropy source whose profile owns the credential.\n */\n async completeMfaEnrollment(\n flowId: string,\n proof: EnrollmentProof,\n entropySourceId?: string,\n ): Promise<void> {\n const accessToken = await this.getAccessToken(entropySourceId);\n await mfaEnrollComplete(this.#config.env, accessToken, {\n credential_type: proof.type,\n flow_id: flowId,\n ...(proof.type === 'passkey'\n ? { passkey_attestation: proof.attestation }\n : { otp_code: proof.code }),\n });\n }\n\n /**\n * Begins step-up verification with an enrolled credential.\n *\n * @param type - Credential type to verify.\n * @param entropySourceId - Entropy source whose profile owns the credential.\n * @returns Verification challenge for the client ceremony.\n */\n async beginMfaVerification(\n type: MfaCredentialType,\n entropySourceId?: string,\n ): Promise<StepUpChallenge> {\n const accessToken = await this.getAccessToken(entropySourceId);\n const result = await mfaVerify(this.#config.env, accessToken, {\n credential_type: type,\n });\n\n if (type === 'passkey') {\n if (!result.publicKey) {\n throw new MfaError(\n 'invalid_response',\n 'Passkey verification response is missing request data',\n );\n }\n return {\n type,\n flowId: result.flowId,\n expiresAt: result.expiresAt,\n publicKey: result.publicKey,\n };\n }\n return {\n type,\n flowId: result.flowId,\n expiresAt: result.expiresAt,\n };\n }\n\n /**\n * Completes step-up verification with an enrolled credential.\n *\n * @param flowId - Identifier returned by the begin call.\n * @param proof - Platform assertion or email code.\n * @param entropySourceId - Entropy source whose profile owns the credential.\n * @returns AAL2 assertion issued after verification.\n */\n async completeMfaVerification(\n flowId: string,\n proof: StepUpProof,\n entropySourceId?: string,\n ): Promise<MfaStepUpAssertion> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await mfaVerifyComplete(this.#config.env, accessToken, {\n credential_type: proof.type,\n flow_id: flowId,\n ...(proof.type === 'passkey'\n ? { passkey_assertion: proof.assertion }\n : { otp_code: proof.code }),\n });\n }\n\n /**\n * Gets credentials enrolled on the primary profile.\n *\n * @param entropySourceId - Entropy source whose profile owns the credentials.\n * @returns Supported enrolled credentials.\n */\n async getMfaCredentials(\n entropySourceId?: string,\n ): Promise<EnrolledCredential[]> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await getMfaCredentials(this.#config.env, accessToken);\n }\n\n /**\n * Exchanges an MFA assertion for an elevated access token.\n *\n * @param assertionJwt - AAL2 authentication assertion.\n * @returns Elevated access token.\n */\n async exchangeMfaAssertion(assertionJwt: string): Promise<AccessToken> {\n return await authorizeOIDC(\n assertionJwt,\n this.#config.env,\n this.#config.platform,\n );\n }\n\n async pairSocialIdentifier(\n params: PairSocialIdentifierParams,\n authAccessToken: string,\n ): Promise<void> {\n await pairSocialIdentifier(params, authAccessToken, this.#config.env);\n }\n\n async pairSrpProfiles(\n accessTokens: string[],\n authAccessToken: string,\n ): Promise<PairProfilesResponse> {\n // Order-insensitive key: the same token set in any order maps to the same\n // entry. Sort a copy so the request payload itself stays primary-first.\n const key = JSON.stringify([...accessTokens].sort());\n\n const cached = this.#ongoingPairings.get(key);\n if (cached && cached.expiresAt > Date.now()) {\n return await cached.promise;\n }\n\n const promise = pairProfiles(\n accessTokens,\n authAccessToken,\n this.#config.env,\n );\n // Store the in-flight promise immediately so concurrent callers coalesce\n // regardless of how long the request takes.\n this.#ongoingPairings.set(key, {\n promise,\n expiresAt: Number.MAX_SAFE_INTEGER,\n });\n\n try {\n const result = await promise;\n // Keep the resolved result cached for a short window so sequential\n // retries with the same payload reuse it.\n this.#ongoingPairings.set(key, {\n promise,\n expiresAt: Date.now() + PAIR_DEDUPE_TTL_MS,\n });\n return result;\n } catch (error) {\n // Never cache failures: the pairing retry loop must be able to re-hit\n // the endpoint on the next attempt.\n this.#ongoingPairings.delete(key);\n throw error;\n }\n }\n\n async signMessage(\n message: string,\n entropySourceId?: string,\n ): Promise<string> {\n return await this.#options.signing.signMessage(message, entropySourceId);\n }\n\n async isSnapConnected(): Promise<boolean> {\n const provider =\n this.#customProvider ?? (await getDefaultEIP6963Provider());\n if (!provider) {\n return false;\n }\n\n const isConnected = await isSnapConnected(provider);\n return isConnected;\n }\n\n async connectSnap(): Promise<string> {\n const provider =\n this.#customProvider ?? (await getDefaultEIP6963Provider());\n\n const res = await connectSnap(provider);\n return res;\n }\n\n // convert expiresIn from seconds to milliseconds and use 90% of expiresIn\n async #getAuthSession(\n entropySourceId?: string,\n ): Promise<LoginResponse | null> {\n const auth = await this.#options.storage.getLoginResponse(entropySourceId);\n if (!validateLoginResponse(auth)) {\n return null;\n }\n\n // get canonical profile id from server if not present in the cached session\n if (!auth.profile.canonicalProfileId) {\n return null;\n }\n\n const currentTime = Date.now();\n const sessionAge = currentTime - auth.token.obtainedAt;\n const refreshThreshold = auth.token.expiresIn * 1000 * 0.9;\n\n if (sessionAge < refreshThreshold) {\n return auth;\n }\n return null;\n }\n\n async #login(entropySourceId?: string): Promise<LoginResponse> {\n // Use a deferred login to avoid race conditions\n return await this.#deferredLogin(entropySourceId);\n }\n\n async #performLogin(entropySourceId?: string): Promise<LoginResponse> {\n // Nonce\n const publicKey = await this.getIdentifier(entropySourceId);\n const nonceRes = await getNonce(publicKey, this.#config.env);\n\n // Tag only when the wallet supplies getLoginTag. SDK callers keep the\n // legacy 3-part message rather than guessing `primary`.\n const tag = await this.#getLoginTag?.(entropySourceId);\n const identifierType =\n (await this.#getLoginIdentifierType?.(entropySourceId)) ?? 'SRP';\n const rawMessage = this.#createSrpLoginRawMessage(\n nonceRes.nonce,\n publicKey,\n tag,\n );\n const signature = await this.signMessage(rawMessage, entropySourceId);\n\n // Authenticate\n const authResponse = await authenticate(\n rawMessage,\n signature,\n this.#config.type,\n this.#config.env,\n this.#metametrics,\n identifierType,\n );\n\n // Resolve original profileId from aliases.\n // This is done mainly to preserve the original profileId for storage key derivation\n // until we migrate to the canonical profileId storage system.\n const canonicalProfileId = authResponse.profile.profileId;\n const profile = { ...authResponse.profile };\n\n if (authResponse.profileAliases?.length > 0) {\n const targetIdentifierId = computeIdentifierId(\n publicKey,\n this.#config.env,\n );\n\n const matchingAliases = authResponse.profileAliases.filter((alias) =>\n alias.identifierIds.some((id) => id.id === targetIdentifierId),\n );\n\n // Prefer the leaf alias (single identifier) — it's the original profile\n // created for this SRP. Multi-identifier aliases are former canonicals\n // that absorbed other profiles; they are correct only when this SRP's\n // original profile was itself a canonical before being absorbed.\n const targetAlias =\n matchingAliases.find((alias) => alias.identifierIds.length === 1) ??\n matchingAliases[0];\n\n if (targetAlias) {\n profile.profileId = targetAlias.aliasProfileId;\n }\n }\n\n profile.canonicalProfileId = canonicalProfileId;\n\n // Authorize\n const tokenResponse = await authorizeOIDC(\n authResponse.token,\n this.#config.env,\n this.#config.platform,\n );\n\n // Save\n const result: LoginResponse = {\n profile,\n token: tokenResponse,\n };\n\n await this.#options.storage.setLoginResponse(result, entropySourceId);\n\n return result;\n }\n\n async #deferredLogin(entropySourceId?: string): Promise<LoginResponse> {\n // Check if there's already an ongoing login for this entropySourceId\n const existingLogin = this.#ongoingLogins.get(entropySourceId);\n if (existingLogin) {\n return existingLogin;\n }\n\n // Create a new login promise\n const loginPromise = this.#loginWithRetry(entropySourceId);\n\n // Store the promise in the map\n this.#ongoingLogins.set(entropySourceId, loginPromise);\n\n try {\n // Wait for the login to complete\n return await loginPromise;\n } finally {\n // Always clean up the ongoing login promise when done\n this.#ongoingLogins.delete(entropySourceId);\n }\n }\n\n async #loginWithRetry(entropySourceId?: string): Promise<LoginResponse> {\n // Allow max attempts: initial + maxLoginRetries on 429\n for (let attempt = 0; attempt < 1 + this.#maxLoginRetries; attempt += 1) {\n try {\n return await this.#performLogin(entropySourceId);\n } catch (e) {\n // Only retry on rate-limit (429) errors\n if (!RateLimitedError.isRateLimitError(e)) {\n throw e;\n }\n\n // If we've exhausted attempts, rethrow\n if (attempt >= this.#maxLoginRetries) {\n throw e;\n }\n\n // Wait for Retry-After or default cooldown\n const waitMs = e.retryAfterMs ?? this.#cooldownDefaultMs;\n await timeUtils.delay(waitMs);\n\n // Loop continues to retry\n }\n }\n\n // Should never reach here due to loop logic, but TypeScript needs a return\n throw new Error('Unexpected: login loop exhausted without result');\n }\n\n #createSrpLoginRawMessage(\n nonce: string,\n publicKey: string,\n tag?: SrpLoginTag,\n ):\n | `metamask:${string}:${string}`\n | `metamask:${string}:${string}:${SrpLoginTag}` {\n if (tag) {\n return `metamask:${nonce}:${publicKey}:${tag}` as const;\n }\n return `metamask:${nonce}:${publicKey}` as const;\n }\n}\n"]}
1
+ {"version":3,"file":"flow-srp.js","sourceRoot":"","sources":["../../../src/sdk/authentication-jwt-bearer/flow-srp.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,MAAM,wCAAwC,CAAC;AACpF,OAAO,EACL,oBAAoB,EACpB,+BAA+B,EAC/B,WAAW,EACX,eAAe,GAChB,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAC5E,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,iBAAiB,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;QAC5C,uDAAuD;QACvD,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,CAAC,GAAG,IAAI,CAAC,gBAAgB,EAAE,OAAO,IAAI,CAAC,EAAE,CAAC;YACxE,IAAI,CAAC;gBACH,OAAO,MAAM,IAAI,CAAC,aAAa,CAAC,eAAe,CAAC,CAAC;YACnD,CAAC;YAAC,OAAO,CAAC,EAAE,CAAC;gBACX,wCAAwC;gBACxC,IAAI,CAAC,gBAAgB,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,CAAC;oBAC1C,MAAM,CAAC,CAAC;gBACV,CAAC;gBAED,uCAAuC;gBACvC,IAAI,OAAO,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;oBACrC,MAAM,CAAC,CAAC;gBACV,CAAC;gBAED,2CAA2C;gBAC3C,MAAM,MAAM,GAAG,CAAC,CAAC,YAAY,IAAI,IAAI,CAAC,kBAAkB,CAAC;gBACzD,MAAM,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;gBAE9B,0BAA0B;YAC5B,CAAC;QACH,CAAC;QAED,2EAA2E;QAC3E,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACrE,CAAC;IAED,yBAAyB,CACvB,KAAa,EACb,SAAiB,EACjB,GAAiB;QAIjB,IAAI,GAAG,EAAE,CAAC;YACR,OAAO,YAAY,KAAK,IAAI,SAAS,IAAI,GAAG,EAAW,CAAC;QAC1D,CAAC;QACD,OAAO,YAAY,KAAK,IAAI,SAAS,EAAW,CAAC;IACnD,CAAC;CACF","sourcesContent":["import type { Eip1193Provider } from 'ethers';\n\nimport type { MetaMetricsAuth } from '../../shared/types/services.js';\nimport { MfaError, ValidationError, RateLimitedError } from '../errors.js';\nimport { getMetaMaskProviderEIP6963 } from '../utils/eip-6963-metamask-provider.js';\nimport {\n MESSAGE_SIGNING_SNAP,\n assertMessageStartsWithMetamask,\n connectSnap,\n isSnapConnected,\n} from '../utils/messaging-signing-snap-requests.js';\nimport { validateLoginResponse } from '../utils/validate-login-response.js';\nimport {\n getMfaCredentials,\n mfaEnroll,\n mfaEnrollComplete,\n mfaVerify,\n mfaVerifyComplete,\n} from './mfa/services.js';\nimport type { MfaStepUpAssertion } from './mfa/services.js';\nimport type {\n EnrolledCredential,\n EnrollmentChallenge,\n EnrollmentProof,\n MfaCredentialType,\n StepUpChallenge,\n StepUpProof,\n} from './mfa/types.js';\nimport {\n authenticate,\n authorizeOIDC,\n getCustomerServiceToken,\n getNonce,\n getPartnerIdentityToken,\n getUserProfileLineage,\n pairProfiles,\n pairSocialIdentifier,\n} from './services.js';\nimport type { PairProfilesResponse } from './services.js';\nimport type {\n AuthConfig,\n AccessToken,\n AuthSigningOptions,\n AuthStorageOptions,\n AuthType,\n IBaseAuth,\n LoginIdentifierType,\n LoginResponse,\n OidcTokenAudience,\n OidcTokenClaims,\n PairSocialIdentifierParams,\n ProfileIdentifier,\n SrpLoginTag,\n UserProfile,\n UserProfileLineage,\n} from './types.js';\nimport { computeIdentifierId } from './utils/identifier.js';\nimport * as timeUtils from './utils/time.js';\n\ntype JwtBearerAuth_SRP_Options = {\n storage: AuthStorageOptions;\n signing?: AuthSigningOptions;\n /**\n * Resolves the login tag for a given entropy source.\n * When omitted, `raw_message` stays untagged (`metamask:<nonce>:<pubkey>`).\n */\n getLoginTag?: (entropySourceId?: string) => Promise<SrpLoginTag>;\n /**\n * Resolves the metametrics `identifier_type` for a given entropy source.\n * Defaults to `'SRP'` when omitted.\n */\n getLoginIdentifierType?: (\n entropySourceId?: string,\n ) => Promise<LoginIdentifierType>;\n rateLimitRetry?: {\n cooldownDefaultMs?: number; // default cooldown when 429 has no Retry-After\n maxLoginRetries?: number; // maximum number of login retries on rate limit\n };\n};\n\n// How long a successful pairing result stays cached so identical payloads\n// (concurrent or sequential retries) reuse it instead of re-hitting the endpoint.\nexport const PAIR_DEDUPE_TTL_MS = 30_000;\n\nconst getDefaultEIP6963Provider = async () => {\n const provider = await getMetaMaskProviderEIP6963();\n if (!provider) {\n throw new ValidationError('No MetaMask wallet connected');\n }\n return provider;\n};\n\nconst getDefaultEIP6963SigningOptions = (\n customProvider?: Eip1193Provider,\n): AuthSigningOptions => ({\n getIdentifier: async (entropySourceId?: string): Promise<string> => {\n const provider = customProvider ?? (await getDefaultEIP6963Provider());\n return await MESSAGE_SIGNING_SNAP.getPublicKey(provider, entropySourceId);\n },\n signMessage: async (\n message: string,\n entropySourceId?: string,\n ): Promise<string> => {\n const provider = customProvider ?? (await getDefaultEIP6963Provider());\n assertMessageStartsWithMetamask(message);\n return await MESSAGE_SIGNING_SNAP.signMessage(\n provider,\n message,\n entropySourceId,\n );\n },\n});\n\nexport class SRPJwtBearerAuth implements IBaseAuth {\n readonly #config: AuthConfig;\n\n readonly #options: {\n storage: AuthStorageOptions;\n signing: AuthSigningOptions;\n };\n\n readonly #metametrics?: MetaMetricsAuth;\n\n // Map to store ongoing login promises by entropySourceId\n readonly #ongoingLogins = new Map<\n string | undefined,\n Promise<LoginResponse>\n >();\n\n // Map to dedupe pairing calls by an order-insensitive token-set key.\n // Holds the in-flight promise (coalescing concurrent callers) and keeps it\n // for a short TTL after success (collapsing sequential retries).\n readonly #ongoingPairings = new Map<\n string,\n { promise: Promise<PairProfilesResponse>; expiresAt: number }\n >();\n\n // Default cooldown when 429 has no Retry-After header\n readonly #cooldownDefaultMs: number;\n\n // Maximum number of login retries on rate limit errors\n readonly #maxLoginRetries: number;\n\n readonly #getLoginTag?: (entropySourceId?: string) => Promise<SrpLoginTag>;\n\n readonly #getLoginIdentifierType?: (\n entropySourceId?: string,\n ) => Promise<LoginIdentifierType>;\n\n #customProvider?: Eip1193Provider;\n\n constructor(\n config: AuthConfig & { type: AuthType.SRP },\n options: JwtBearerAuth_SRP_Options & {\n customProvider?: Eip1193Provider;\n metametrics?: MetaMetricsAuth;\n },\n ) {\n this.#config = config;\n this.#customProvider = options.customProvider;\n this.#getLoginTag = options.getLoginTag;\n this.#getLoginIdentifierType = options.getLoginIdentifierType;\n this.#options = {\n storage: options.storage,\n signing:\n options.signing ??\n getDefaultEIP6963SigningOptions(this.#customProvider),\n };\n this.#metametrics = options.metametrics;\n\n // Apply rate limit retry config if provided\n this.#cooldownDefaultMs =\n options.rateLimitRetry?.cooldownDefaultMs ?? 10000;\n this.#maxLoginRetries = options.rateLimitRetry?.maxLoginRetries ?? 1;\n }\n\n setCustomProvider(provider: Eip1193Provider) {\n this.#customProvider = provider;\n this.#options.signing = getDefaultEIP6963SigningOptions(provider);\n }\n\n // TODO: might be easier to keep entropySourceId as a class param and use multiple SRPJwtBearerAuth instances where needed\n async getAccessToken(entropySourceId?: string): Promise<string> {\n const session = await this.#getAuthSession(entropySourceId);\n if (session) {\n return session.token.accessToken;\n }\n\n const loginResponse = await this.#login(entropySourceId);\n return loginResponse.token.accessToken;\n }\n\n async getUserProfile(entropySourceId?: string): Promise<UserProfile> {\n const session = await this.#getAuthSession(entropySourceId);\n if (session) {\n return session.profile;\n }\n\n const loginResponse = await this.#login(entropySourceId);\n return loginResponse.profile;\n }\n\n async getIdentifier(entropySourceId?: string): Promise<string> {\n return await this.#options.signing.getIdentifier(entropySourceId);\n }\n\n async getUserProfileLineage(\n entropySourceId?: string,\n ): Promise<UserProfileLineage> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await getUserProfileLineage(this.#config.env, accessToken);\n }\n\n async getCustomerServiceToken(entropySourceId?: string): Promise<string> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await getCustomerServiceToken(this.#config.env, accessToken);\n }\n\n async getPartnerIdentityToken(\n claims: OidcTokenClaims,\n audience: OidcTokenAudience,\n entropySourceId?: string,\n ): Promise<string> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await getPartnerIdentityToken(\n this.#config.env,\n accessToken,\n claims,\n audience,\n );\n }\n\n /**\n * Begins enrollment of an MFA credential for the primary profile.\n *\n * @param type - Credential type to enroll.\n * @param options - Enrollment options.\n * @param options.email - Email address, required for email OTP.\n * @param options.entropySourceId - Entropy source whose profile owns the\n * credential.\n * @param options.accessToken - Bearer to use instead of the base session\n * token; an elevated token is required once a credential is already enrolled.\n * @returns Enrollment challenge for the client ceremony.\n */\n async beginMfaEnrollment(\n type: MfaCredentialType,\n options?: {\n email?: string;\n entropySourceId?: string;\n accessToken?: string;\n },\n ): Promise<EnrollmentChallenge> {\n const { email, entropySourceId } = options ?? {};\n const accessToken =\n options?.accessToken ?? (await this.getAccessToken(entropySourceId));\n const result = await mfaEnroll(this.#config.env, accessToken, {\n credential_type: type,\n ...(email ? { identifier: email } : {}),\n });\n\n if (type === 'passkey') {\n if (!result.publicKey) {\n throw new MfaError(\n 'invalid_response',\n 'Passkey enrollment response is missing creation data',\n );\n }\n return {\n type,\n flowId: result.flowId,\n expiresAt: result.expiresAt,\n publicKey: result.publicKey,\n };\n }\n return {\n type,\n flowId: result.flowId,\n expiresAt: result.expiresAt,\n };\n }\n\n /**\n * Completes enrollment of an MFA credential.\n *\n * @param flowId - Identifier returned by the begin call.\n * @param proof - Platform attestation or email code.\n * @param entropySourceId - Entropy source whose profile owns the credential.\n */\n async completeMfaEnrollment(\n flowId: string,\n proof: EnrollmentProof,\n entropySourceId?: string,\n ): Promise<void> {\n const accessToken = await this.getAccessToken(entropySourceId);\n await mfaEnrollComplete(this.#config.env, accessToken, {\n credential_type: proof.type,\n flow_id: flowId,\n ...(proof.type === 'passkey'\n ? { passkey_attestation: proof.attestation }\n : { otp_code: proof.code }),\n });\n }\n\n /**\n * Begins step-up verification with an enrolled credential.\n *\n * @param type - Credential type to verify.\n * @param entropySourceId - Entropy source whose profile owns the credential.\n * @returns Verification challenge for the client ceremony.\n */\n async beginMfaVerification(\n type: MfaCredentialType,\n entropySourceId?: string,\n ): Promise<StepUpChallenge> {\n const accessToken = await this.getAccessToken(entropySourceId);\n const result = await mfaVerify(this.#config.env, accessToken, {\n credential_type: type,\n });\n\n if (type === 'passkey') {\n if (!result.publicKey) {\n throw new MfaError(\n 'invalid_response',\n 'Passkey verification response is missing request data',\n );\n }\n return {\n type,\n flowId: result.flowId,\n expiresAt: result.expiresAt,\n publicKey: result.publicKey,\n };\n }\n return {\n type,\n flowId: result.flowId,\n expiresAt: result.expiresAt,\n };\n }\n\n /**\n * Completes step-up verification with an enrolled credential.\n *\n * @param flowId - Identifier returned by the begin call.\n * @param proof - Platform assertion or email code.\n * @param entropySourceId - Entropy source whose profile owns the credential.\n * @returns AAL2 assertion issued after verification.\n */\n async completeMfaVerification(\n flowId: string,\n proof: StepUpProof,\n entropySourceId?: string,\n ): Promise<MfaStepUpAssertion> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await mfaVerifyComplete(this.#config.env, accessToken, {\n credential_type: proof.type,\n flow_id: flowId,\n ...(proof.type === 'passkey'\n ? { passkey_assertion: proof.assertion }\n : { otp_code: proof.code }),\n });\n }\n\n /**\n * Gets credentials enrolled on the primary profile.\n *\n * @param entropySourceId - Entropy source whose profile owns the credentials.\n * @returns Supported enrolled credentials.\n */\n async getMfaCredentials(\n entropySourceId?: string,\n ): Promise<EnrolledCredential[]> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await getMfaCredentials(this.#config.env, accessToken);\n }\n\n /**\n * Exchanges an MFA assertion for an elevated access token.\n *\n * @param assertionJwt - AAL2 authentication assertion.\n * @returns Elevated access token.\n */\n async exchangeMfaAssertion(assertionJwt: string): Promise<AccessToken> {\n return await authorizeOIDC(\n assertionJwt,\n this.#config.env,\n this.#config.platform,\n );\n }\n\n async pairSocialIdentifier(\n params: PairSocialIdentifierParams,\n authAccessToken: string,\n ): Promise<ProfileIdentifier[] | undefined> {\n return await pairSocialIdentifier(\n params,\n authAccessToken,\n this.#config.env,\n );\n }\n\n async pairSrpProfiles(\n accessTokens: string[],\n authAccessToken: string,\n ): Promise<PairProfilesResponse> {\n // Order-insensitive key: the same token set in any order maps to the same\n // entry. Sort a copy so the request payload itself stays primary-first.\n const key = JSON.stringify([...accessTokens].sort());\n\n const cached = this.#ongoingPairings.get(key);\n if (cached && cached.expiresAt > Date.now()) {\n return await cached.promise;\n }\n\n const promise = pairProfiles(\n accessTokens,\n authAccessToken,\n this.#config.env,\n );\n // Store the in-flight promise immediately so concurrent callers coalesce\n // regardless of how long the request takes.\n this.#ongoingPairings.set(key, {\n promise,\n expiresAt: Number.MAX_SAFE_INTEGER,\n });\n\n try {\n const result = await promise;\n // Keep the resolved result cached for a short window so sequential\n // retries with the same payload reuse it.\n this.#ongoingPairings.set(key, {\n promise,\n expiresAt: Date.now() + PAIR_DEDUPE_TTL_MS,\n });\n return result;\n } catch (error) {\n // Never cache failures: the pairing retry loop must be able to re-hit\n // the endpoint on the next attempt.\n this.#ongoingPairings.delete(key);\n throw error;\n }\n }\n\n async signMessage(\n message: string,\n entropySourceId?: string,\n ): Promise<string> {\n return await this.#options.signing.signMessage(message, entropySourceId);\n }\n\n async isSnapConnected(): Promise<boolean> {\n const provider =\n this.#customProvider ?? (await getDefaultEIP6963Provider());\n if (!provider) {\n return false;\n }\n\n const isConnected = await isSnapConnected(provider);\n return isConnected;\n }\n\n async connectSnap(): Promise<string> {\n const provider =\n this.#customProvider ?? (await getDefaultEIP6963Provider());\n\n const res = await connectSnap(provider);\n return res;\n }\n\n // convert expiresIn from seconds to milliseconds and use 90% of expiresIn\n async #getAuthSession(\n entropySourceId?: string,\n ): Promise<LoginResponse | null> {\n const auth = await this.#options.storage.getLoginResponse(entropySourceId);\n if (!validateLoginResponse(auth)) {\n return null;\n }\n\n // get canonical profile id from server if not present in the cached session\n if (!auth.profile.canonicalProfileId) {\n return null;\n }\n\n const currentTime = Date.now();\n const sessionAge = currentTime - auth.token.obtainedAt;\n const refreshThreshold = auth.token.expiresIn * 1000 * 0.9;\n\n if (sessionAge < refreshThreshold) {\n return auth;\n }\n return null;\n }\n\n async #login(entropySourceId?: string): Promise<LoginResponse> {\n // Use a deferred login to avoid race conditions\n return await this.#deferredLogin(entropySourceId);\n }\n\n async #performLogin(entropySourceId?: string): Promise<LoginResponse> {\n // Nonce\n const publicKey = await this.getIdentifier(entropySourceId);\n const nonceRes = await getNonce(publicKey, this.#config.env);\n\n // Tag only when the wallet supplies getLoginTag. SDK callers keep the\n // legacy 3-part message rather than guessing `primary`.\n const tag = await this.#getLoginTag?.(entropySourceId);\n const identifierType =\n (await this.#getLoginIdentifierType?.(entropySourceId)) ?? 'SRP';\n const rawMessage = this.#createSrpLoginRawMessage(\n nonceRes.nonce,\n publicKey,\n tag,\n );\n const signature = await this.signMessage(rawMessage, entropySourceId);\n\n // Authenticate\n const authResponse = await authenticate(\n rawMessage,\n signature,\n this.#config.type,\n this.#config.env,\n this.#metametrics,\n identifierType,\n );\n\n // Resolve original profileId from aliases.\n // This is done mainly to preserve the original profileId for storage key derivation\n // until we migrate to the canonical profileId storage system.\n const canonicalProfileId = authResponse.profile.profileId;\n const profile = { ...authResponse.profile };\n\n if (authResponse.profileAliases?.length > 0) {\n const targetIdentifierId = computeIdentifierId(\n publicKey,\n this.#config.env,\n );\n\n const matchingAliases = authResponse.profileAliases.filter((alias) =>\n alias.identifierIds.some((id) => id.id === targetIdentifierId),\n );\n\n // Prefer the leaf alias (single identifier) — it's the original profile\n // created for this SRP. Multi-identifier aliases are former canonicals\n // that absorbed other profiles; they are correct only when this SRP's\n // original profile was itself a canonical before being absorbed.\n const targetAlias =\n matchingAliases.find((alias) => alias.identifierIds.length === 1) ??\n matchingAliases[0];\n\n if (targetAlias) {\n profile.profileId = targetAlias.aliasProfileId;\n }\n }\n\n profile.canonicalProfileId = canonicalProfileId;\n\n // Authorize\n const tokenResponse = await authorizeOIDC(\n authResponse.token,\n this.#config.env,\n this.#config.platform,\n );\n\n // Save\n const result: LoginResponse = {\n profile,\n token: tokenResponse,\n };\n\n await this.#options.storage.setLoginResponse(result, entropySourceId);\n\n return result;\n }\n\n async #deferredLogin(entropySourceId?: string): Promise<LoginResponse> {\n // Check if there's already an ongoing login for this entropySourceId\n const existingLogin = this.#ongoingLogins.get(entropySourceId);\n if (existingLogin) {\n return existingLogin;\n }\n\n // Create a new login promise\n const loginPromise = this.#loginWithRetry(entropySourceId);\n\n // Store the promise in the map\n this.#ongoingLogins.set(entropySourceId, loginPromise);\n\n try {\n // Wait for the login to complete\n return await loginPromise;\n } finally {\n // Always clean up the ongoing login promise when done\n this.#ongoingLogins.delete(entropySourceId);\n }\n }\n\n async #loginWithRetry(entropySourceId?: string): Promise<LoginResponse> {\n // Allow max attempts: initial + maxLoginRetries on 429\n for (let attempt = 0; attempt < 1 + this.#maxLoginRetries; attempt += 1) {\n try {\n return await this.#performLogin(entropySourceId);\n } catch (e) {\n // Only retry on rate-limit (429) errors\n if (!RateLimitedError.isRateLimitError(e)) {\n throw e;\n }\n\n // If we've exhausted attempts, rethrow\n if (attempt >= this.#maxLoginRetries) {\n throw e;\n }\n\n // Wait for Retry-After or default cooldown\n const waitMs = e.retryAfterMs ?? this.#cooldownDefaultMs;\n await timeUtils.delay(waitMs);\n\n // Loop continues to retry\n }\n }\n\n // Should never reach here due to loop logic, but TypeScript needs a return\n throw new Error('Unexpected: login loop exhausted without result');\n }\n\n #createSrpLoginRawMessage(\n nonce: string,\n publicKey: string,\n tag?: SrpLoginTag,\n ):\n | `metamask:${string}:${string}`\n | `metamask:${string}:${string}:${SrpLoginTag}` {\n if (tag) {\n return `metamask:${nonce}:${publicKey}:${tag}` as const;\n }\n return `metamask:${nonce}:${publicKey}` as const;\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { Env, Platform } from '../../shared/env.js';
2
2
  import type { MetaMetricsAuth } from '../../shared/types/services.js';
3
- import type { AccessToken, LoginIdentifierType, OidcTokenAudience, OidcTokenClaims, PairSocialIdentifierParams, ProfileAlias, UserProfile, UserProfileLineage } from './types.js';
3
+ import type { AccessToken, LoginIdentifierType, OidcTokenAudience, OidcTokenClaims, PairSocialIdentifierParams, ProfileAlias, ProfileIdentifier, UserProfile, UserProfileLineage } from './types.js';
4
4
  import { AuthType } from './types.js';
5
5
  export declare const NONCE_URL: (env: Env) => string;
6
6
  export declare const PAIR_IDENTIFIERS: (env: Env) => string;
@@ -52,15 +52,14 @@ export declare function pairProfiles(accessTokens: string[], authAccessToken: st
52
52
  * owns `authAccessToken` (`POST /api/v2/profile/pair/identifier`).
53
53
  *
54
54
  * `email` is omitted from the body when undefined. 409 Conflict throws
55
- * {@link PairConflictError} so callers can treat it as terminal. The
56
- * response body (new token + profile) is not consumed: a 2xx status is the
57
- * only success signal.
55
+ * {@link PairConflictError} so callers can treat it as terminal.
58
56
  *
59
57
  * @param params - Social identifier type, social JWT, and optional email
60
58
  * @param authAccessToken - Bearer token of the canonical (primary SRP) profile
61
59
  * @param env - server environment
60
+ * @returns The profile's paired identifiers, if returned by the API
62
61
  */
63
- export declare function pairSocialIdentifier(params: PairSocialIdentifierParams, authAccessToken: string, env: Env): Promise<void>;
62
+ export declare function pairSocialIdentifier(params: PairSocialIdentifierParams, authAccessToken: string, env: Env): Promise<ProfileIdentifier[] | undefined>;
64
63
  /**
65
64
  * Service to Get Nonce for JWT Bearer Flow
66
65
  *
@@ -1 +1 @@
1
- {"version":3,"file":"services.d.ts","sourceRoot":"","sources":["../../../src/sdk/authentication-jwt-bearer/services.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEzD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAYtE,OAAO,KAAK,EACV,WAAW,EAEX,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,0BAA0B,EAC1B,YAAY,EACZ,WAAW,EACX,kBAAkB,EACnB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAwHtC,eAAO,MAAM,SAAS,QAAS,GAAG,KAAG,MACS,CAAC;AAE/C,eAAO,MAAM,gBAAgB,QAAS,GAAG,KAAG,MACa,CAAC;AAE1D,eAAO,MAAM,cAAc,QAAS,GAAG,KAAG,MACI,CAAC;AAE/C,e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,GAAE,mBAA2B,GAC1C,OAAO,CAAC,cAAc,CAAC,CAyDzB;AAED;;;;;;GAMG;AACH,wBAAsB,qBAAqB,CACzC,GAAG,EAAE,GAAG,EACR,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,kBAAkB,CAAC,CA4B7B;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,uBAAuB,CAC3C,GAAG,EAAE,GAAG,EACR,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,MAAM,CAAC,CAiCjB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,uBAAuB,CAC3C,GAAG,EAAE,GAAG,EACR,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,eAAe,EACvB,QAAQ,EAAE,iBAAiB,GAC1B,OAAO,CAAC,MAAM,CAAC,CAuCjB"}
@@ -193,6 +193,7 @@ export async function pairProfiles(accessTokens, authAccessToken, env) {
193
193
  metaMetricsId: pairResponse.profile.metametrics_id ?? '',
194
194
  profileId: pairResponse.profile.profile_id,
195
195
  canonicalProfileId: pairResponse.profile.profile_id,
196
+ pairedIdentifierIds: pairResponse.profile.paired_identifier_ids,
196
197
  },
197
198
  profileAliases: parseProfileAliases(pairResponse.profile_aliases ?? []),
198
199
  };
@@ -206,13 +207,12 @@ export async function pairProfiles(accessTokens, authAccessToken, env) {
206
207
  * owns `authAccessToken` (`POST /api/v2/profile/pair/identifier`).
207
208
  *
208
209
  * `email` is omitted from the body when undefined. 409 Conflict throws
209
- * {@link PairConflictError} so callers can treat it as terminal. The
210
- * response body (new token + profile) is not consumed: a 2xx status is the
211
- * only success signal.
210
+ * {@link PairConflictError} so callers can treat it as terminal.
212
211
  *
213
212
  * @param params - Social identifier type, social JWT, and optional email
214
213
  * @param authAccessToken - Bearer token of the canonical (primary SRP) profile
215
214
  * @param env - server environment
215
+ * @returns The profile's paired identifiers, if returned by the API
216
216
  */
217
217
  export async function pairSocialIdentifier(params, authAccessToken, env) {
218
218
  const pairUrl = new URL(PAIR_SOCIAL_IDENTIFIER_URL(env));
@@ -236,9 +236,11 @@ export async function pairSocialIdentifier(params, authAccessToken, env) {
236
236
  }
237
237
  await throwServiceError(response, errorPrefix, PairError);
238
238
  }
239
+ const pairResponse = await response.json();
240
+ return pairResponse.profile.paired_identifier_ids;
239
241
  }
240
242
  catch (error) {
241
- await throwServiceError(error, errorPrefix, PairError);
243
+ return await throwServiceError(error, errorPrefix, PairError);
242
244
  }
243
245
  }
244
246
  /**
@@ -354,6 +356,7 @@ export async function authenticate(rawMessage, signature, authType, env, metamet
354
356
  metaMetricsId: loginResponse.profile.metametrics_id,
355
357
  profileId: loginResponse.profile.profile_id,
356
358
  canonicalProfileId: loginResponse.profile.profile_id,
359
+ pairedIdentifierIds: loginResponse.profile.paired_identifier_ids,
357
360
  },
358
361
  profileAliases: parseProfileAliases(loginResponse.profile_aliases ?? []),
359
362
  };
@@ -1 +1 @@
1
- {"version":3,"file":"services.js","sourceRoot":"","sources":["../../../src/sdk/authentication-jwt-bearer/services.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAElE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,SAAS,EACT,WAAW,EACX,eAAe,EACf,gBAAgB,GACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAY1E,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC;;;;;;GAMG;AACH,SAAS,eAAe,CAAC,gBAA+B;IACtD,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;IACzC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;QAC3B,OAAO,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AAY,KAAK,QAAQ,EAAE,CAAC;YACpD,MAAM,IAAI,WAAW,CAAC,GAAG,WAAW,wBAAwB,CAAC,CAAC;QAChE,CAAC;QACD,OAAO,aAAa,CAAC,YAAY,CAAC;IACpC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,kBAAkB,EAAE,CAAC;YACxC,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,MAAM,iBAAiB,CAAC,KAAK,EAAE,WAAW,EAAE,WAAW,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import type { Env, Platform } from '../../shared/env.js';\nimport { getEnvUrls, getOidcClientId } from '../../shared/env.js';\nimport type { MetaMetricsAuth } from '../../shared/types/services.js';\nimport { HTTP_STATUS_CODES } from '../constants.js';\nimport {\n NonceRetrievalError,\n EmailRequiredError,\n PairConflictError,\n PairError,\n SignInError,\n ValidationError,\n RateLimitedError,\n} from '../errors.js';\nimport { validatePairResponse } from '../utils/validate-pair-response.js';\nimport type {\n AccessToken,\n ErrorMessage,\n LoginIdentifierType,\n OidcTokenAudience,\n OidcTokenClaims,\n PairSocialIdentifierParams,\n ProfileAlias,\n UserProfile,\n UserProfileLineage,\n} from './types.js';\nimport { AuthType } from './types.js';\n\n/**\n * Parse Retry-After header into milliseconds if possible.\n * Supports seconds or HTTP-date formats.\n *\n * @param retryAfterHeader - The Retry-After header value (seconds or HTTP-date)\n * @returns The retry delay in milliseconds, or null if parsing fails\n */\nfunction parseRetryAfter(retryAfterHeader: string | null): number | null {\n if (!retryAfterHeader) {\n return null;\n }\n const seconds = Number(retryAfterHeader);\n if (!Number.isNaN(seconds)) {\n return seconds * 1000;\n }\n const date = Date.parse(retryAfterHeader);\n if (!Number.isNaN(date)) {\n const diff = date - Date.now();\n return diff > 0 ? diff : null;\n }\n return null;\n}\n\n/**\n * Extracts error details from a Response object.\n *\n * @param response - The HTTP response object\n * @returns Formatted error message with HTTP status and response body\n */\nasync function getResponseErrorMessage(response: Response): Promise<string> {\n const { status } = response;\n const clonedResponse = response.clone();\n\n let message = 'Unknown error';\n let error = 'unknown';\n\n try {\n const responseBody = (await response.json()) as\n | ErrorMessage\n // eslint-disable-next-line @typescript-eslint/naming-convention\n | { error_description: string; error: string };\n\n message =\n 'message' in responseBody\n ? responseBody.message\n : responseBody.error_description;\n error = responseBody.error ?? 'unknown';\n } catch {\n try {\n const textContent = await clonedResponse.text();\n message = textContent\n ? textContent.slice(0, 150)\n : 'Non-JSON error response';\n error = 'non_json_response';\n } catch {\n message = 'Unable to parse error response';\n error = 'unparseable_response';\n }\n }\n\n return `HTTP ${status} - ${message} (error: ${error})`;\n}\n\n/**\n * Type guard to check if an object is a Response-like object.\n *\n * @param obj - The object to check\n * @returns True if the object is a Response-like object, false otherwise\n */\nconst isErrorResponse = (obj: unknown): obj is Response =>\n typeof obj === 'object' &&\n obj !== null &&\n 'status' in obj &&\n 'headers' in obj;\n\n/**\n * Throws a domain-specific error for service failures.\n * Handles both HTTP error responses and regular errors (network failures, etc.).\n * For HTTP 429, throws RateLimitedError with Retry-After header parsing.\n *\n * @param error - The error (Response object or caught error)\n * @param errorPrefix - Context prefix for the error message\n * @param ErrorClass - The domain-specific error class to throw\n * @throws RateLimitedError for 429, otherwise ErrorClass\n */\nasync function throwServiceError(\n error: unknown,\n errorPrefix: string,\n ErrorClass: new (message: string) => Error,\n): Promise<never> {\n // Re-throw RateLimitedError or matching ErrorClass as-is (don't double-wrap)\n if (error instanceof RateLimitedError || error instanceof ErrorClass) {\n throw error;\n }\n\n // Not a Response-like object - handle as regular error\n if (!isErrorResponse(error)) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new ErrorClass(`${errorPrefix}: ${errorMessage}`);\n }\n\n // Handle HTTP error response\n const response = error;\n const { status } = response;\n const responseMessage = await getResponseErrorMessage(response);\n\n if (status === HTTP_STATUS_CODES.TOO_MANY_REQUESTS) {\n const retryAfterHeader = response.headers.get('Retry-After');\n const retryAfterMs = parseRetryAfter(retryAfterHeader);\n throw new RateLimitedError(\n `${errorPrefix}: ${responseMessage}`,\n retryAfterMs ?? undefined,\n );\n }\n\n throw new ErrorClass(`${errorPrefix}: ${responseMessage}`);\n}\n\nexport const NONCE_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/nonce`;\n\nexport const PAIR_IDENTIFIERS = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/identifiers/pair`;\n\nexport const OIDC_TOKEN_URL = (env: Env): string =>\n `${getEnvUrls(env).oidcApiUrl}/oauth2/token`;\n\nexport const SRP_LOGIN_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/srp/login`;\n\nexport const SIWE_LOGIN_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/siwe/login`;\n\nexport const PAIR_PROFILES_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/profile/pair`;\n\nexport const PAIR_SOCIAL_IDENTIFIER_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/profile/pair/identifier`;\n\nexport const PROFILE_LINEAGE_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/profile/lineage`;\n\nexport const CUSTOMER_SERVICE_TOKEN_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/customer-service/token`;\n\nexport const PARTNER_IDENTITY_TOKEN_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/oidc/token`;\n\nconst getAuthenticationUrl = (authType: AuthType, env: Env): string => {\n switch (authType) {\n case AuthType.SRP:\n return SRP_LOGIN_URL(env);\n case AuthType.SiWE:\n return SIWE_LOGIN_URL(env);\n /* istanbul ignore next */\n default:\n throw new ValidationError(\n `Invalid AuthType: ${authType as number} - unable to create Auth URL`,\n );\n }\n};\n\ntype NonceResponse = {\n nonce: string;\n identifier: string;\n expiresIn: number;\n};\n\ntype RawProfileAlias = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n alias_profile_id: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n canonical_profile_id: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n identifier_ids: { id: string; type: string }[];\n};\n\nconst parseProfileAliases = (raw: RawProfileAlias[]): ProfileAlias[] => {\n return raw.map((alias) => ({\n aliasProfileId: alias.alias_profile_id,\n canonicalProfileId: alias.canonical_profile_id,\n identifierIds: alias.identifier_ids ?? [],\n }));\n};\n\ntype PairRequest = {\n signature: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n raw_message: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n encrypted_storage_key: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n identifier_type: 'SIWE' | 'SRP';\n};\n\n/**\n * Pair multiple identifiers under a single profile\n *\n * @param nonce - session nonce\n * @param logins - pairing request payload\n * @param accessToken - JWT access token used to access protected resources\n * @param env - server environment\n * @returns void.\n */\nexport async function pairIdentifiers(\n nonce: string,\n logins: PairRequest[],\n accessToken: string,\n env: Env,\n): Promise<void> {\n const pairUrl = new URL(PAIR_IDENTIFIERS(env));\n\n try {\n const response = await fetch(pairUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify({\n nonce,\n logins,\n }),\n });\n\n if (!response.ok) {\n return await throwServiceError(\n response,\n 'Failed to pair identifiers',\n PairError,\n );\n }\n return undefined;\n } catch (error) {\n return await throwServiceError(\n error,\n 'Failed to pair identifiers',\n PairError,\n );\n }\n}\n\nexport type PairProfilesResponse = {\n profile: UserProfile;\n profileAliases: ProfileAlias[];\n};\n\n/**\n * Pair multiple profiles using their OIDC access tokens.\n * Idempotent — calling with already-paired tokens is a no-op.\n *\n * @param accessTokens - Two or more OIDC access tokens to pair\n * @param authAccessToken - A valid access token for the Authorization header\n * @param env - server environment\n * @returns The pair response containing the canonical profile and aliases\n */\nexport async function pairProfiles(\n accessTokens: string[],\n authAccessToken: string,\n env: Env,\n): Promise<PairProfilesResponse> {\n const pairUrl = new URL(PAIR_PROFILES_URL(env));\n\n try {\n const response = await fetch(pairUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${authAccessToken}`,\n },\n body: JSON.stringify({\n jwts: accessTokens,\n }),\n });\n\n if (!response.ok) {\n return await throwServiceError(\n response,\n 'Failed to pair profiles',\n PairError,\n );\n }\n\n const pairResponse: unknown = await response.json();\n validatePairResponse(pairResponse);\n\n return {\n profile: {\n identifierId: pairResponse.profile.identifier_id,\n metaMetricsId: pairResponse.profile.metametrics_id ?? '',\n profileId: pairResponse.profile.profile_id,\n canonicalProfileId: pairResponse.profile.profile_id,\n },\n profileAliases: parseProfileAliases(pairResponse.profile_aliases ?? []),\n };\n } catch (error) {\n return await throwServiceError(error, 'Failed to pair profiles', PairError);\n }\n}\n\n/**\n * Attach a Google/Apple/Telegram social identifier to the profile that\n * owns `authAccessToken` (`POST /api/v2/profile/pair/identifier`).\n *\n * `email` is omitted from the body when undefined. 409 Conflict throws\n * {@link PairConflictError} so callers can treat it as terminal. The\n * response body (new token + profile) is not consumed: a 2xx status is the\n * only success signal.\n *\n * @param params - Social identifier type, social JWT, and optional email\n * @param authAccessToken - Bearer token of the canonical (primary SRP) profile\n * @param env - server environment\n */\nexport async function pairSocialIdentifier(\n params: PairSocialIdentifierParams,\n authAccessToken: string,\n env: Env,\n): Promise<void> {\n const pairUrl = new URL(PAIR_SOCIAL_IDENTIFIER_URL(env));\n const errorPrefix = 'Failed to pair social identifier';\n\n try {\n const response = await fetch(pairUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${authAccessToken}`,\n },\n body: JSON.stringify({\n identifier_type: params.identifierType,\n social_jwt: params.socialJwt,\n ...(params.email === undefined ? {} : { email: params.email }),\n }),\n });\n\n if (!response.ok) {\n if (response.status === HTTP_STATUS_CODES.CONFLICT) {\n await throwServiceError(response, errorPrefix, PairConflictError);\n }\n await throwServiceError(response, errorPrefix, PairError);\n }\n } catch (error) {\n await throwServiceError(error, errorPrefix, PairError);\n }\n}\n\n/**\n * Service to Get Nonce for JWT Bearer Flow\n *\n * @param id - identifier ID\n * @param env - server environment\n * @returns the nonce.\n */\nexport async function getNonce(id: string, env: Env): Promise<NonceResponse> {\n const nonceUrl = new URL(NONCE_URL(env));\n nonceUrl.searchParams.set('identifier', id);\n\n try {\n const nonceResponse = await fetch(nonceUrl.toString());\n if (!nonceResponse.ok) {\n return await throwServiceError(\n nonceResponse,\n 'Failed to get nonce',\n NonceRetrievalError,\n );\n }\n\n const nonceJson = await nonceResponse.json();\n return {\n nonce: nonceJson.nonce,\n identifier: nonceJson.identifier,\n expiresIn: nonceJson.expires_in,\n };\n } catch (error) {\n return await throwServiceError(\n error,\n 'Failed to get nonce',\n NonceRetrievalError,\n );\n }\n}\n\n/**\n * Service to Authorize And perform OIDC Flow to get the Access Token\n *\n * @param jwtToken - The original token received from Authentication. This is traded for the Access Token. (the authentication token is single-use)\n * @param env - server environment\n * @param platform - SDK platform\n * @returns Access Token from Authorization server\n */\nexport async function authorizeOIDC(\n jwtToken: string,\n env: Env,\n platform: Platform,\n): Promise<AccessToken> {\n const grantType = 'urn:ietf:params:oauth:grant-type:jwt-bearer';\n const headers = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n const urlEncodedBody = new URLSearchParams();\n urlEncodedBody.append('grant_type', grantType);\n urlEncodedBody.append('client_id', getOidcClientId(env, platform));\n urlEncodedBody.append('assertion', jwtToken);\n\n try {\n const response = await fetch(OIDC_TOKEN_URL(env), {\n method: 'POST',\n headers,\n body: urlEncodedBody.toString(),\n });\n\n if (!response.ok) {\n return await throwServiceError(\n response,\n 'Failed to get access token',\n SignInError,\n );\n }\n\n const accessTokenResponse = await response.json();\n return {\n accessToken: accessTokenResponse.access_token,\n expiresIn: accessTokenResponse.expires_in,\n obtainedAt: Date.now(),\n };\n } catch (error) {\n return await throwServiceError(\n error,\n 'Failed to get access token',\n SignInError,\n );\n }\n}\n\ntype Authentication = {\n token: string;\n expiresIn: number;\n profile: UserProfile;\n profileAliases: ProfileAlias[];\n};\n/**\n * Service to Authenticate/Login a user via SIWE or SRP derived key.\n *\n * @param rawMessage - raw message for validation when authenticating\n * @param signature - signed raw message\n * @param authType - authentication type/flow used\n * @param env - server environment\n * @param metametrics - optional metametrics\n * @param identifierType - login identifier type included in metametrics\n * (defaults to `SRP` when metametrics is present)\n * @returns Authentication Token\n */\nexport async function authenticate(\n rawMessage: string,\n signature: string,\n authType: AuthType,\n env: Env,\n metametrics?: MetaMetricsAuth,\n identifierType: LoginIdentifierType = 'SRP',\n): Promise<Authentication> {\n const authenticationUrl = getAuthenticationUrl(authType, env);\n\n try {\n const response = await fetch(authenticationUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(authType === AuthType.SRP\n ? { 'X-MetaMask-Profile-Pairing': 'enabled' }\n : {}),\n },\n body: JSON.stringify({\n signature,\n raw_message: rawMessage,\n ...(metametrics\n ? {\n metametrics: {\n metametrics_id: await metametrics.getMetaMetricsId(),\n agent: metametrics.agent,\n app_version: await metametrics.getAppVersion?.(),\n identifier_type: identifierType,\n },\n }\n : {}),\n }),\n });\n\n if (!response.ok) {\n return await throwServiceError(\n response,\n `Failed to login with ${authType}`,\n SignInError,\n );\n }\n\n const loginResponse = await response.json();\n\n return {\n token: loginResponse.token,\n expiresIn: loginResponse.expires_in,\n profile: {\n identifierId: loginResponse.profile.identifier_id,\n metaMetricsId: loginResponse.profile.metametrics_id,\n profileId: loginResponse.profile.profile_id,\n canonicalProfileId: loginResponse.profile.profile_id,\n },\n profileAliases: parseProfileAliases(loginResponse.profile_aliases ?? []),\n };\n } catch (error) {\n return await throwServiceError(\n error,\n `Failed to login with ${authType}`,\n SignInError,\n );\n }\n}\n\n/**\n * Service to get the Profile Lineage\n *\n * @param env - server environment\n * @param accessToken - JWT access token used to access protected resources\n * @returns Profile Lineage information.\n */\nexport async function getUserProfileLineage(\n env: Env,\n accessToken: string,\n): Promise<UserProfileLineage> {\n const profileLineageUrl = new URL(PROFILE_LINEAGE_URL(env));\n\n try {\n const response = await fetch(profileLineageUrl, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${accessToken}`,\n },\n });\n\n if (!response.ok) {\n return await throwServiceError(\n response,\n 'Failed to get profile lineage',\n SignInError,\n );\n }\n\n const profileJson: UserProfileLineage = await response.json();\n return profileJson;\n } catch (error) {\n return await throwServiceError(\n error,\n 'Failed to get profile lineage',\n SignInError,\n );\n }\n}\n\n/**\n * Service to get a Customer Service specific access token.\n *\n * Exchanges a valid OIDC access token for a short-lived token scoped to the\n * customer-service audience, which Customer Service tooling consumes to\n * identify and authenticate the user.\n *\n * @param env - server environment\n * @param accessToken - JWT access token used to access protected resources\n * @returns The customer-service access token.\n */\nexport async function getCustomerServiceToken(\n env: Env,\n accessToken: string,\n): Promise<string> {\n const customerServiceTokenUrl = new URL(CUSTOMER_SERVICE_TOKEN_URL(env));\n\n try {\n const response = await fetch(customerServiceTokenUrl, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${accessToken}`,\n },\n });\n\n if (!response.ok) {\n return await throwServiceError(\n response,\n 'Failed to get customer service token',\n SignInError,\n );\n }\n\n const tokenResponse = await response.json();\n if (typeof tokenResponse?.access_token !== 'string') {\n throw new SignInError(\n 'Failed to get customer service token: missing access_token',\n );\n }\n return tokenResponse.access_token;\n } catch (error) {\n return await throwServiceError(\n error,\n 'Failed to get customer service token',\n SignInError,\n );\n }\n}\n\n/**\n * Mint a partner identity token (`POST /api/v2/oidc/token`).\n *\n * Exchanges a Hydra login bearer for a short-lived JWT scoped to `audience`\n * (`kyc` / `iron`) with the requested claims. Email lands under JWT `ext`\n * on live tokens. Returns only `access_token`.\n *\n * @param env - server environment\n * @param accessToken - Hydra JWT used to access protected resources\n * @param claims - claim names to embed (only `email` is supported)\n * @param audience - partner audience stamped on the minted JWT\n * @returns The partner identity access token.\n * @throws EmailRequiredError when the profile has no verified email (HTTP 422)\n */\nexport async function getPartnerIdentityToken(\n env: Env,\n accessToken: string,\n claims: OidcTokenClaims,\n audience: OidcTokenAudience,\n): Promise<string> {\n const partnerIdentityTokenUrl = new URL(PARTNER_IDENTITY_TOKEN_URL(env));\n const errorPrefix = 'Failed to get partner identity token';\n\n try {\n const response = await fetch(partnerIdentityTokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify({\n claims,\n audience,\n }),\n });\n\n if (!response.ok) {\n if (response.status === HTTP_STATUS_CODES.UNPROCESSABLE_ENTITY) {\n return await throwServiceError(\n response,\n errorPrefix,\n EmailRequiredError,\n );\n }\n return await throwServiceError(response, errorPrefix, SignInError);\n }\n\n const tokenResponse = await response.json();\n if (typeof tokenResponse?.access_token !== 'string') {\n throw new SignInError(`${errorPrefix}: missing access_token`);\n }\n return tokenResponse.access_token;\n } catch (error) {\n if (error instanceof EmailRequiredError) {\n throw error;\n }\n return await throwServiceError(error, errorPrefix, SignInError);\n }\n}\n"]}
1
+ {"version":3,"file":"services.js","sourceRoot":"","sources":["../../../src/sdk/authentication-jwt-bearer/services.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAElE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,SAAS,EACT,WAAW,EACX,eAAe,EACf,gBAAgB,GACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAa1E,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC;;;;;;GAMG;AACH,SAAS,eAAe,CAAC,gBAA+B;IACtD,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,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,CAAC;YACjB,IAAI,QAAQ,CAAC,MAAM,KAAK,iBAAiB,CAAC,oBAAoB,EAAE,CAAC;gBAC/D,OAAO,MAAM,iBAAiB,CAC5B,QAAQ,EACR,WAAW,EACX,kBAAkB,CACnB,CAAC;YACJ,CAAC;YACD,OAAO,MAAM,iBAAiB,CAAC,QAAQ,EAAE,WAAW,EAAE,WAAW,CAAC,CAAC;QACrE,CAAC;QAED,MAAM,aAAa,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAC5C,IAAI,OAAO,aAAa,EAAE,YAAY,KAAK,QAAQ,EAAE,CAAC;YACpD,MAAM,IAAI,WAAW,CAAC,GAAG,WAAW,wBAAwB,CAAC,CAAC;QAChE,CAAC;QACD,OAAO,aAAa,CAAC,YAAY,CAAC;IACpC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,kBAAkB,EAAE,CAAC;YACxC,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,MAAM,iBAAiB,CAAC,KAAK,EAAE,WAAW,EAAE,WAAW,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import type { Env, Platform } from '../../shared/env.js';\nimport { getEnvUrls, getOidcClientId } from '../../shared/env.js';\nimport type { MetaMetricsAuth } from '../../shared/types/services.js';\nimport { HTTP_STATUS_CODES } from '../constants.js';\nimport {\n NonceRetrievalError,\n EmailRequiredError,\n PairConflictError,\n PairError,\n SignInError,\n ValidationError,\n RateLimitedError,\n} from '../errors.js';\nimport { validatePairResponse } from '../utils/validate-pair-response.js';\nimport type {\n AccessToken,\n ErrorMessage,\n LoginIdentifierType,\n OidcTokenAudience,\n OidcTokenClaims,\n PairSocialIdentifierParams,\n ProfileAlias,\n ProfileIdentifier,\n UserProfile,\n UserProfileLineage,\n} from './types.js';\nimport { AuthType } from './types.js';\n\n/**\n * Parse Retry-After header into milliseconds if possible.\n * Supports seconds or HTTP-date formats.\n *\n * @param retryAfterHeader - The Retry-After header value (seconds or HTTP-date)\n * @returns The retry delay in milliseconds, or null if parsing fails\n */\nfunction parseRetryAfter(retryAfterHeader: string | null): number | null {\n if (!retryAfterHeader) {\n return null;\n }\n const seconds = Number(retryAfterHeader);\n if (!Number.isNaN(seconds)) {\n return seconds * 1000;\n }\n const date = Date.parse(retryAfterHeader);\n if (!Number.isNaN(date)) {\n const diff = date - Date.now();\n return diff > 0 ? diff : null;\n }\n return null;\n}\n\n/**\n * Extracts error details from a Response object.\n *\n * @param response - The HTTP response object\n * @returns Formatted error message with HTTP status and response body\n */\nasync function getResponseErrorMessage(response: Response): Promise<string> {\n const { status } = response;\n const clonedResponse = response.clone();\n\n let message = 'Unknown error';\n let error = 'unknown';\n\n try {\n const responseBody = (await response.json()) as\n | ErrorMessage\n // eslint-disable-next-line @typescript-eslint/naming-convention\n | { error_description: string; error: string };\n\n message =\n 'message' in responseBody\n ? responseBody.message\n : responseBody.error_description;\n error = responseBody.error ?? 'unknown';\n } catch {\n try {\n const textContent = await clonedResponse.text();\n message = textContent\n ? textContent.slice(0, 150)\n : 'Non-JSON error response';\n error = 'non_json_response';\n } catch {\n message = 'Unable to parse error response';\n error = 'unparseable_response';\n }\n }\n\n return `HTTP ${status} - ${message} (error: ${error})`;\n}\n\n/**\n * Type guard to check if an object is a Response-like object.\n *\n * @param obj - The object to check\n * @returns True if the object is a Response-like object, false otherwise\n */\nconst isErrorResponse = (obj: unknown): obj is Response =>\n typeof obj === 'object' &&\n obj !== null &&\n 'status' in obj &&\n 'headers' in obj;\n\n/**\n * Throws a domain-specific error for service failures.\n * Handles both HTTP error responses and regular errors (network failures, etc.).\n * For HTTP 429, throws RateLimitedError with Retry-After header parsing.\n *\n * @param error - The error (Response object or caught error)\n * @param errorPrefix - Context prefix for the error message\n * @param ErrorClass - The domain-specific error class to throw\n * @throws RateLimitedError for 429, otherwise ErrorClass\n */\nasync function throwServiceError(\n error: unknown,\n errorPrefix: string,\n ErrorClass: new (message: string) => Error,\n): Promise<never> {\n // Re-throw RateLimitedError or matching ErrorClass as-is (don't double-wrap)\n if (error instanceof RateLimitedError || error instanceof ErrorClass) {\n throw error;\n }\n\n // Not a Response-like object - handle as regular error\n if (!isErrorResponse(error)) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new ErrorClass(`${errorPrefix}: ${errorMessage}`);\n }\n\n // Handle HTTP error response\n const response = error;\n const { status } = response;\n const responseMessage = await getResponseErrorMessage(response);\n\n if (status === HTTP_STATUS_CODES.TOO_MANY_REQUESTS) {\n const retryAfterHeader = response.headers.get('Retry-After');\n const retryAfterMs = parseRetryAfter(retryAfterHeader);\n throw new RateLimitedError(\n `${errorPrefix}: ${responseMessage}`,\n retryAfterMs ?? undefined,\n );\n }\n\n throw new ErrorClass(`${errorPrefix}: ${responseMessage}`);\n}\n\nexport const NONCE_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/nonce`;\n\nexport const PAIR_IDENTIFIERS = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/identifiers/pair`;\n\nexport const OIDC_TOKEN_URL = (env: Env): string =>\n `${getEnvUrls(env).oidcApiUrl}/oauth2/token`;\n\nexport const SRP_LOGIN_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/srp/login`;\n\nexport const SIWE_LOGIN_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/siwe/login`;\n\nexport const PAIR_PROFILES_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/profile/pair`;\n\nexport const PAIR_SOCIAL_IDENTIFIER_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/profile/pair/identifier`;\n\nexport const PROFILE_LINEAGE_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/profile/lineage`;\n\nexport const CUSTOMER_SERVICE_TOKEN_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/customer-service/token`;\n\nexport const PARTNER_IDENTITY_TOKEN_URL = (env: Env): string =>\n `${getEnvUrls(env).authApiUrl}/api/v2/oidc/token`;\n\nconst getAuthenticationUrl = (authType: AuthType, env: Env): string => {\n switch (authType) {\n case AuthType.SRP:\n return SRP_LOGIN_URL(env);\n case AuthType.SiWE:\n return SIWE_LOGIN_URL(env);\n /* istanbul ignore next */\n default:\n throw new ValidationError(\n `Invalid AuthType: ${authType as number} - unable to create Auth URL`,\n );\n }\n};\n\ntype NonceResponse = {\n nonce: string;\n identifier: string;\n expiresIn: number;\n};\n\ntype RawProfileAlias = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n alias_profile_id: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n canonical_profile_id: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n identifier_ids: { id: string; type: string }[];\n};\n\nconst parseProfileAliases = (raw: RawProfileAlias[]): ProfileAlias[] => {\n return raw.map((alias) => ({\n aliasProfileId: alias.alias_profile_id,\n canonicalProfileId: alias.canonical_profile_id,\n identifierIds: alias.identifier_ids ?? [],\n }));\n};\n\ntype PairRequest = {\n signature: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n raw_message: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n encrypted_storage_key: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n identifier_type: 'SIWE' | 'SRP';\n};\n\n/**\n * Pair multiple identifiers under a single profile\n *\n * @param nonce - session nonce\n * @param logins - pairing request payload\n * @param accessToken - JWT access token used to access protected resources\n * @param env - server environment\n * @returns void.\n */\nexport async function pairIdentifiers(\n nonce: string,\n logins: PairRequest[],\n accessToken: string,\n env: Env,\n): Promise<void> {\n const pairUrl = new URL(PAIR_IDENTIFIERS(env));\n\n try {\n const response = await fetch(pairUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify({\n nonce,\n logins,\n }),\n });\n\n if (!response.ok) {\n return await throwServiceError(\n response,\n 'Failed to pair identifiers',\n PairError,\n );\n }\n return undefined;\n } catch (error) {\n return await throwServiceError(\n error,\n 'Failed to pair identifiers',\n PairError,\n );\n }\n}\n\nexport type PairProfilesResponse = {\n profile: UserProfile;\n profileAliases: ProfileAlias[];\n};\n\n/**\n * Pair multiple profiles using their OIDC access tokens.\n * Idempotent — calling with already-paired tokens is a no-op.\n *\n * @param accessTokens - Two or more OIDC access tokens to pair\n * @param authAccessToken - A valid access token for the Authorization header\n * @param env - server environment\n * @returns The pair response containing the canonical profile and aliases\n */\nexport async function pairProfiles(\n accessTokens: string[],\n authAccessToken: string,\n env: Env,\n): Promise<PairProfilesResponse> {\n const pairUrl = new URL(PAIR_PROFILES_URL(env));\n\n try {\n const response = await fetch(pairUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${authAccessToken}`,\n },\n body: JSON.stringify({\n jwts: accessTokens,\n }),\n });\n\n if (!response.ok) {\n return await throwServiceError(\n response,\n 'Failed to pair profiles',\n PairError,\n );\n }\n\n const pairResponse: unknown = await response.json();\n validatePairResponse(pairResponse);\n\n return {\n profile: {\n identifierId: pairResponse.profile.identifier_id,\n metaMetricsId: pairResponse.profile.metametrics_id ?? '',\n profileId: pairResponse.profile.profile_id,\n canonicalProfileId: pairResponse.profile.profile_id,\n pairedIdentifierIds: pairResponse.profile.paired_identifier_ids,\n },\n profileAliases: parseProfileAliases(pairResponse.profile_aliases ?? []),\n };\n } catch (error) {\n return await throwServiceError(error, 'Failed to pair profiles', PairError);\n }\n}\n\n/**\n * Attach a Google/Apple/Telegram social identifier to the profile that\n * owns `authAccessToken` (`POST /api/v2/profile/pair/identifier`).\n *\n * `email` is omitted from the body when undefined. 409 Conflict throws\n * {@link PairConflictError} so callers can treat it as terminal.\n *\n * @param params - Social identifier type, social JWT, and optional email\n * @param authAccessToken - Bearer token of the canonical (primary SRP) profile\n * @param env - server environment\n * @returns The profile's paired identifiers, if returned by the API\n */\nexport async function pairSocialIdentifier(\n params: PairSocialIdentifierParams,\n authAccessToken: string,\n env: Env,\n): Promise<ProfileIdentifier[] | undefined> {\n const pairUrl = new URL(PAIR_SOCIAL_IDENTIFIER_URL(env));\n const errorPrefix = 'Failed to pair social identifier';\n\n try {\n const response = await fetch(pairUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${authAccessToken}`,\n },\n body: JSON.stringify({\n identifier_type: params.identifierType,\n social_jwt: params.socialJwt,\n ...(params.email === undefined ? {} : { email: params.email }),\n }),\n });\n\n if (!response.ok) {\n if (response.status === HTTP_STATUS_CODES.CONFLICT) {\n await throwServiceError(response, errorPrefix, PairConflictError);\n }\n await throwServiceError(response, errorPrefix, PairError);\n }\n\n const pairResponse = await response.json();\n return pairResponse.profile.paired_identifier_ids;\n } catch (error) {\n return await throwServiceError(error, errorPrefix, PairError);\n }\n}\n\n/**\n * Service to Get Nonce for JWT Bearer Flow\n *\n * @param id - identifier ID\n * @param env - server environment\n * @returns the nonce.\n */\nexport async function getNonce(id: string, env: Env): Promise<NonceResponse> {\n const nonceUrl = new URL(NONCE_URL(env));\n nonceUrl.searchParams.set('identifier', id);\n\n try {\n const nonceResponse = await fetch(nonceUrl.toString());\n if (!nonceResponse.ok) {\n return await throwServiceError(\n nonceResponse,\n 'Failed to get nonce',\n NonceRetrievalError,\n );\n }\n\n const nonceJson = await nonceResponse.json();\n return {\n nonce: nonceJson.nonce,\n identifier: nonceJson.identifier,\n expiresIn: nonceJson.expires_in,\n };\n } catch (error) {\n return await throwServiceError(\n error,\n 'Failed to get nonce',\n NonceRetrievalError,\n );\n }\n}\n\n/**\n * Service to Authorize And perform OIDC Flow to get the Access Token\n *\n * @param jwtToken - The original token received from Authentication. This is traded for the Access Token. (the authentication token is single-use)\n * @param env - server environment\n * @param platform - SDK platform\n * @returns Access Token from Authorization server\n */\nexport async function authorizeOIDC(\n jwtToken: string,\n env: Env,\n platform: Platform,\n): Promise<AccessToken> {\n const grantType = 'urn:ietf:params:oauth:grant-type:jwt-bearer';\n const headers = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n const urlEncodedBody = new URLSearchParams();\n urlEncodedBody.append('grant_type', grantType);\n urlEncodedBody.append('client_id', getOidcClientId(env, platform));\n urlEncodedBody.append('assertion', jwtToken);\n\n try {\n const response = await fetch(OIDC_TOKEN_URL(env), {\n method: 'POST',\n headers,\n body: urlEncodedBody.toString(),\n });\n\n if (!response.ok) {\n return await throwServiceError(\n response,\n 'Failed to get access token',\n SignInError,\n );\n }\n\n const accessTokenResponse = await response.json();\n return {\n accessToken: accessTokenResponse.access_token,\n expiresIn: accessTokenResponse.expires_in,\n obtainedAt: Date.now(),\n };\n } catch (error) {\n return await throwServiceError(\n error,\n 'Failed to get access token',\n SignInError,\n );\n }\n}\n\ntype Authentication = {\n token: string;\n expiresIn: number;\n profile: UserProfile;\n profileAliases: ProfileAlias[];\n};\n/**\n * Service to Authenticate/Login a user via SIWE or SRP derived key.\n *\n * @param rawMessage - raw message for validation when authenticating\n * @param signature - signed raw message\n * @param authType - authentication type/flow used\n * @param env - server environment\n * @param metametrics - optional metametrics\n * @param identifierType - login identifier type included in metametrics\n * (defaults to `SRP` when metametrics is present)\n * @returns Authentication Token\n */\nexport async function authenticate(\n rawMessage: string,\n signature: string,\n authType: AuthType,\n env: Env,\n metametrics?: MetaMetricsAuth,\n identifierType: LoginIdentifierType = 'SRP',\n): Promise<Authentication> {\n const authenticationUrl = getAuthenticationUrl(authType, env);\n\n try {\n const response = await fetch(authenticationUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(authType === AuthType.SRP\n ? { 'X-MetaMask-Profile-Pairing': 'enabled' }\n : {}),\n },\n body: JSON.stringify({\n signature,\n raw_message: rawMessage,\n ...(metametrics\n ? {\n metametrics: {\n metametrics_id: await metametrics.getMetaMetricsId(),\n agent: metametrics.agent,\n app_version: await metametrics.getAppVersion?.(),\n identifier_type: identifierType,\n },\n }\n : {}),\n }),\n });\n\n if (!response.ok) {\n return await throwServiceError(\n response,\n `Failed to login with ${authType}`,\n SignInError,\n );\n }\n\n const loginResponse = await response.json();\n\n return {\n token: loginResponse.token,\n expiresIn: loginResponse.expires_in,\n profile: {\n identifierId: loginResponse.profile.identifier_id,\n metaMetricsId: loginResponse.profile.metametrics_id,\n profileId: loginResponse.profile.profile_id,\n canonicalProfileId: loginResponse.profile.profile_id,\n pairedIdentifierIds: loginResponse.profile.paired_identifier_ids,\n },\n profileAliases: parseProfileAliases(loginResponse.profile_aliases ?? []),\n };\n } catch (error) {\n return await throwServiceError(\n error,\n `Failed to login with ${authType}`,\n SignInError,\n );\n }\n}\n\n/**\n * Service to get the Profile Lineage\n *\n * @param env - server environment\n * @param accessToken - JWT access token used to access protected resources\n * @returns Profile Lineage information.\n */\nexport async function getUserProfileLineage(\n env: Env,\n accessToken: string,\n): Promise<UserProfileLineage> {\n const profileLineageUrl = new URL(PROFILE_LINEAGE_URL(env));\n\n try {\n const response = await fetch(profileLineageUrl, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${accessToken}`,\n },\n });\n\n if (!response.ok) {\n return await throwServiceError(\n response,\n 'Failed to get profile lineage',\n SignInError,\n );\n }\n\n const profileJson: UserProfileLineage = await response.json();\n return profileJson;\n } catch (error) {\n return await throwServiceError(\n error,\n 'Failed to get profile lineage',\n SignInError,\n );\n }\n}\n\n/**\n * Service to get a Customer Service specific access token.\n *\n * Exchanges a valid OIDC access token for a short-lived token scoped to the\n * customer-service audience, which Customer Service tooling consumes to\n * identify and authenticate the user.\n *\n * @param env - server environment\n * @param accessToken - JWT access token used to access protected resources\n * @returns The customer-service access token.\n */\nexport async function getCustomerServiceToken(\n env: Env,\n accessToken: string,\n): Promise<string> {\n const customerServiceTokenUrl = new URL(CUSTOMER_SERVICE_TOKEN_URL(env));\n\n try {\n const response = await fetch(customerServiceTokenUrl, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${accessToken}`,\n },\n });\n\n if (!response.ok) {\n return await throwServiceError(\n response,\n 'Failed to get customer service token',\n SignInError,\n );\n }\n\n const tokenResponse = await response.json();\n if (typeof tokenResponse?.access_token !== 'string') {\n throw new SignInError(\n 'Failed to get customer service token: missing access_token',\n );\n }\n return tokenResponse.access_token;\n } catch (error) {\n return await throwServiceError(\n error,\n 'Failed to get customer service token',\n SignInError,\n );\n }\n}\n\n/**\n * Mint a partner identity token (`POST /api/v2/oidc/token`).\n *\n * Exchanges a Hydra login bearer for a short-lived JWT scoped to `audience`\n * (`kyc` / `iron`) with the requested claims. Email lands under JWT `ext`\n * on live tokens. Returns only `access_token`.\n *\n * @param env - server environment\n * @param accessToken - Hydra JWT used to access protected resources\n * @param claims - claim names to embed (only `email` is supported)\n * @param audience - partner audience stamped on the minted JWT\n * @returns The partner identity access token.\n * @throws EmailRequiredError when the profile has no verified email (HTTP 422)\n */\nexport async function getPartnerIdentityToken(\n env: Env,\n accessToken: string,\n claims: OidcTokenClaims,\n audience: OidcTokenAudience,\n): Promise<string> {\n const partnerIdentityTokenUrl = new URL(PARTNER_IDENTITY_TOKEN_URL(env));\n const errorPrefix = 'Failed to get partner identity token';\n\n try {\n const response = await fetch(partnerIdentityTokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify({\n claims,\n audience,\n }),\n });\n\n if (!response.ok) {\n if (response.status === HTTP_STATUS_CODES.UNPROCESSABLE_ENTITY) {\n return await throwServiceError(\n response,\n errorPrefix,\n EmailRequiredError,\n );\n }\n return await throwServiceError(response, errorPrefix, SignInError);\n }\n\n const tokenResponse = await response.json();\n if (typeof tokenResponse?.access_token !== 'string') {\n throw new SignInError(`${errorPrefix}: missing access_token`);\n }\n return tokenResponse.access_token;\n } catch (error) {\n if (error instanceof EmailRequiredError) {\n throw error;\n }\n return await throwServiceError(error, errorPrefix, SignInError);\n }\n}\n"]}
@@ -71,6 +71,10 @@ export type AccessToken = {
71
71
  */
72
72
  obtainedAt: number;
73
73
  };
74
+ export type ProfileIdentifier = {
75
+ id: string;
76
+ type: string;
77
+ };
74
78
  export type UserProfile = {
75
79
  /**
76
80
  * The "Identifier" used to log in with.
@@ -91,6 +95,11 @@ export type UserProfile = {
91
95
  * Server MetaMetrics ID. Allows grouping of user events cross platform.
92
96
  */
93
97
  metaMetricsId: string;
98
+ /**
99
+ * All identifiers attached to this profile (SRP, social, MFA).
100
+ * Absent on sessions stored before this field existed.
101
+ */
102
+ pairedIdentifierIds?: ProfileIdentifier[];
94
103
  };
95
104
  /**
96
105
  * Represents a profile alias returned by the server in profile_aliases.
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/sdk/authentication-jwt-bearer/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEzD,oBAAY,QAAQ;IAGlB,GAAG,QAAQ;IAGX,IAAI,SAAS;CACd;AAED;;;;;;GAMG;AACH,MAAM,MAAM,mBAAmB,GAAG,KAAK,GAAG,oBAAoB,CAAC;AAE/D;;;;GAIG;AACH,MAAM,MAAM,oBAAoB,GAAG,QAAQ,GAAG,OAAO,GAAG,UAAU,CAAC;AAEnE;;;GAGG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACvC,cAAc,EAAE,oBAAoB,CAAC;IACrC,SAAS,EAAE,MAAM,CAAC;IAClB;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,cAAc,GAAG,OAAO,CAAC;AAErC;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG,CAAC,cAAc,EAAE,GAAG,cAAc,EAAE,CAAC,CAAC;AAEpE;;GAEG;AACH,MAAM,MAAM,iBAAiB,GAAG,KAAK,GAAG,MAAM,CAAC;AAE/C;;;;;;;GAOG;AACH,MAAM,MAAM,WAAW,GAAG,SAAS,GAAG,WAAW,CAAC;AAElD,MAAM,MAAM,UA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AAM,EAAE,eAAe,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IAC5E,aAAa,EAAE,CAAC,eAAe,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;CAC9D,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,MAAM,MAAM,IAAI,GAAG;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,cAAc,EAAE,MAAM,GAAG,KAAK,CAAC;IAC/B,WAAW,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;CACnD,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE;QACP,cAAc,EAAE,MAAM,CAAC;QACvB,KAAK,EAAE,QAAQ,CAAC;QAChB,UAAU,EAAE,MAAM,CAAC;QACnB,UAAU,EAAE,MAAM,CAAC;QACnB,OAAO,EAAE,MAAM,CAAC;KACjB,EAAE,CAAC;CACL,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/sdk/authentication-jwt-bearer/types.ts"],"names":[],"mappings":"AAEA,MAAM,CAAN,IAAY,QAOX;AAPD,WAAY,QAAQ;IAClB;+DAC2D;IAC3D,uBAAW,CAAA;IAEX,2BAA2B;IAC3B,yBAAa,CAAA;AACf,CAAC,EAPW,QAAQ,KAAR,QAAQ,QAOnB","sourcesContent":["import type { Env, Platform } from '../../shared/env.js';\n\nexport enum AuthType {\n /* sign in using a private key derived from your secret recovery phrase (SRP).\n Uses message signing snap to perform this operation */\n SRP = 'SRP',\n\n /* sign in with Ethereum */\n SiWE = 'SiWE',\n}\n\n/**\n * Login identifier type sent in the `/srp/login` metametrics object.\n * Defaults to `SRP`; social-backed entropy overrides with the OAuth provider.\n *\n * Orthogonal to {@link SrpLoginTag}: a secondary entropy source can still be\n * `GOOGLE` / `APPLE` / `TELEGRAM` if it is social-backed.\n */\nexport type LoginIdentifierType = 'SRP' | SocialIdentifierType;\n\n/**\n * Social identifier types accepted by `POST /api/v2/profile/pair/identifier`.\n * Telegram uses the same Web3Auth access token as Google/Apple; do not send\n * `email` for Telegram (clients store a display name there, not an address).\n */\nexport type SocialIdentifierType = 'GOOGLE' | 'APPLE' | 'TELEGRAM';\n\n/**\n * Parameters for attaching a Google/Apple/Telegram identifier to an\n * existing profile.\n */\nexport type PairSocialIdentifierParams = {\n identifierType: SocialIdentifierType;\n socialJwt: string;\n /**\n * Required by the API for `GOOGLE`. Optional for `APPLE`. Omit for\n * `TELEGRAM`.\n */\n email?: string;\n};\n\n/**\n * Claim names accepted by `POST /api/v2/oidc/token`. Only `email` is\n * supported; `email_verified` is set by the server when email is present.\n */\nexport type OidcTokenClaim = 'email';\n\n/**\n * Non-empty list of claims to embed. The API requires at least one name.\n */\nexport type OidcTokenClaims = [OidcTokenClaim, ...OidcTokenClaim[]];\n\n/**\n * Partner audience stamped on the minted JWT.\n */\nexport type OidcTokenAudience = 'kyc' | 'iron';\n\n/**\n * Tag appended to the SRP login `raw_message` so the auth server can\n * distinguish primary vs secondary SRPs.\n *\n * Message format: `metamask:<nonce>:<pubkey>:<tag>`\n *\n * Orthogonal to {@link LoginIdentifierType}: tag is entropy-slot only.\n */\nexport type SrpLoginTag = 'primary' | 'secondary';\n\nexport type AuthConfig = {\n env: Env;\n platform: Platform;\n type: AuthType;\n};\n\nexport type AccessToken = {\n /**\n * The JWT Access Token\n */\n accessToken: string;\n /**\n * Expiration in seconds\n */\n expiresIn: number;\n /**\n * Date in milliseconds\n */\n obtainedAt: number;\n};\n\nexport type UserProfile = {\n /**\n * The \"Identifier\" used to log in with.\n */\n identifierId: string;\n /**\n * The original per-SRP profile ID. Immutable after first login.\n * Used for user storage key derivation — MUST NOT be replaced with the canonical.\n */\n profileId: string;\n /**\n * The unified canonical profile ID across all paired SRPs.\n * Set from the server response and updated after pairing via canonical propagation.\n * For pre-upgrade state, defaults to profileId.\n */\n canonicalProfileId: string;\n /**\n * Server MetaMetrics ID. Allows grouping of user events cross platform.\n */\n metaMetricsId: string;\n};\n\n/**\n * Represents a profile alias returned by the server in profile_aliases.\n * Transient — this is not persisted in LoginResponse or srpSessionData.\n */\nexport type ProfileAlias = {\n aliasProfileId: string;\n canonicalProfileId: string;\n identifierIds: { id: string; type: string }[];\n};\n\nexport type LoginResponse = {\n token: AccessToken;\n profile: UserProfile;\n};\n\nexport type IBaseAuth = {\n // TODO: figure out if these need the entropy source id param or if that can be abstracted on another layer\n getAccessToken: (entropySourceId?: string) => Promise<string>;\n getUserProfile: (entropySourceId?: string) => Promise<UserProfile>;\n getIdentifier: (entropySourceId?: string) => Promise<string>;\n signMessage: (message: string, entropySourceId?: string) => Promise<string>;\n};\n\nexport type AuthStorageOptions = {\n // TODO: figure out if these need the entropy source id param or if that can be abstracted on another layer\n getLoginResponse: (entropySourceId?: string) => Promise<LoginResponse | null>;\n setLoginResponse: (\n val: LoginResponse,\n entropySourceId?: string,\n ) => Promise<void>;\n};\n\nexport type AuthSigningOptions = {\n // TODO: figure out if these need the entropy source id param or if that can be abstracted on another layer\n signMessage: (message: string, entropySourceId?: string) => Promise<string>;\n getIdentifier: (entropySourceId?: string) => Promise<string>;\n};\n\nexport type ErrorMessage = {\n message: string;\n error: string;\n};\n\nexport type Pair = {\n identifier: string;\n encryptedStorageKey: string;\n identifierType: 'SIWE' | 'SRP';\n signMessage: (message: string) => Promise<string>;\n};\n\nexport type UserProfileLineage = {\n profile_id: string;\n created_at: string;\n lineage: {\n metametrics_id: string;\n agent: Platform;\n created_at: string;\n updated_at: string;\n counter: number;\n }[];\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/sdk/authentication-jwt-bearer/types.ts"],"names":[],"mappings":"AAEA,MAAM,CAAN,IAAY,QAOX;AAPD,WAAY,QAAQ;IAClB;+DAC2D;IAC3D,uBAAW,CAAA;IAEX,2BAA2B;IAC3B,yBAAa,CAAA;AACf,CAAC,EAPW,QAAQ,KAAR,QAAQ,QAOnB","sourcesContent":["import type { Env, Platform } from '../../shared/env.js';\n\nexport enum AuthType {\n /* sign in using a private key derived from your secret recovery phrase (SRP).\n Uses message signing snap to perform this operation */\n SRP = 'SRP',\n\n /* sign in with Ethereum */\n SiWE = 'SiWE',\n}\n\n/**\n * Login identifier type sent in the `/srp/login` metametrics object.\n * Defaults to `SRP`; social-backed entropy overrides with the OAuth provider.\n *\n * Orthogonal to {@link SrpLoginTag}: a secondary entropy source can still be\n * `GOOGLE` / `APPLE` / `TELEGRAM` if it is social-backed.\n */\nexport type LoginIdentifierType = 'SRP' | SocialIdentifierType;\n\n/**\n * Social identifier types accepted by `POST /api/v2/profile/pair/identifier`.\n * Telegram uses the same Web3Auth access token as Google/Apple; do not send\n * `email` for Telegram (clients store a display name there, not an address).\n */\nexport type SocialIdentifierType = 'GOOGLE' | 'APPLE' | 'TELEGRAM';\n\n/**\n * Parameters for attaching a Google/Apple/Telegram identifier to an\n * existing profile.\n */\nexport type PairSocialIdentifierParams = {\n identifierType: SocialIdentifierType;\n socialJwt: string;\n /**\n * Required by the API for `GOOGLE`. Optional for `APPLE`. Omit for\n * `TELEGRAM`.\n */\n email?: string;\n};\n/**\n * Claim names accepted by `POST /api/v2/oidc/token`. Only `email` is\n * supported; `email_verified` is set by the server when email is present.\n */\nexport type OidcTokenClaim = 'email';\n\n/**\n * Non-empty list of claims to embed. The API requires at least one name.\n */\nexport type OidcTokenClaims = [OidcTokenClaim, ...OidcTokenClaim[]];\n\n/**\n * Partner audience stamped on the minted JWT.\n */\nexport type OidcTokenAudience = 'kyc' | 'iron';\n\n/**\n * Tag appended to the SRP login `raw_message` so the auth server can\n * distinguish primary vs secondary SRPs.\n *\n * Message format: `metamask:<nonce>:<pubkey>:<tag>`\n *\n * Orthogonal to {@link LoginIdentifierType}: tag is entropy-slot only.\n */\nexport type SrpLoginTag = 'primary' | 'secondary';\n\nexport type AuthConfig = {\n env: Env;\n platform: Platform;\n type: AuthType;\n};\n\nexport type AccessToken = {\n /**\n * The JWT Access Token\n */\n accessToken: string;\n /**\n * Expiration in seconds\n */\n expiresIn: number;\n /**\n * Date in milliseconds\n */\n obtainedAt: number;\n};\n\nexport type ProfileIdentifier = {\n id: string;\n type: string;\n};\n\nexport type UserProfile = {\n /**\n * The \"Identifier\" used to log in with.\n */\n identifierId: string;\n /**\n * The original per-SRP profile ID. Immutable after first login.\n * Used for user storage key derivation — MUST NOT be replaced with the canonical.\n */\n profileId: string;\n /**\n * The unified canonical profile ID across all paired SRPs.\n * Set from the server response and updated after pairing via canonical propagation.\n * For pre-upgrade state, defaults to profileId.\n */\n canonicalProfileId: string;\n /**\n * Server MetaMetrics ID. Allows grouping of user events cross platform.\n */\n metaMetricsId: string;\n /**\n * All identifiers attached to this profile (SRP, social, MFA).\n * Absent on sessions stored before this field existed.\n */\n pairedIdentifierIds?: ProfileIdentifier[];\n};\n\n/**\n * Represents a profile alias returned by the server in profile_aliases.\n * Transient — this is not persisted in LoginResponse or srpSessionData.\n */\nexport type ProfileAlias = {\n aliasProfileId: string;\n canonicalProfileId: string;\n identifierIds: { id: string; type: string }[];\n};\n\nexport type LoginResponse = {\n token: AccessToken;\n profile: UserProfile;\n};\n\nexport type IBaseAuth = {\n // TODO: figure out if these need the entropy source id param or if that can be abstracted on another layer\n getAccessToken: (entropySourceId?: string) => Promise<string>;\n getUserProfile: (entropySourceId?: string) => Promise<UserProfile>;\n getIdentifier: (entropySourceId?: string) => Promise<string>;\n signMessage: (message: string, entropySourceId?: string) => Promise<string>;\n};\n\nexport type AuthStorageOptions = {\n // TODO: figure out if these need the entropy source id param or if that can be abstracted on another layer\n getLoginResponse: (entropySourceId?: string) => Promise<LoginResponse | null>;\n setLoginResponse: (\n val: LoginResponse,\n entropySourceId?: string,\n ) => Promise<void>;\n};\n\nexport type AuthSigningOptions = {\n // TODO: figure out if these need the entropy source id param or if that can be abstracted on another layer\n signMessage: (message: string, entropySourceId?: string) => Promise<string>;\n getIdentifier: (entropySourceId?: string) => Promise<string>;\n};\n\nexport type ErrorMessage = {\n message: string;\n error: string;\n};\n\nexport type Pair = {\n identifier: string;\n encryptedStorageKey: string;\n identifierType: 'SIWE' | 'SRP';\n signMessage: (message: string) => Promise<string>;\n};\n\nexport type UserProfileLineage = {\n profile_id: string;\n created_at: string;\n lineage: {\n metametrics_id: string;\n agent: Platform;\n created_at: string;\n updated_at: string;\n counter: number;\n }[];\n};\n"]}
@@ -5,7 +5,7 @@ import { SRPJwtBearerAuth } from './authentication-jwt-bearer/flow-srp.js';
5
5
  import type { MfaStepUpAssertion } from './authentication-jwt-bearer/mfa/services.js';
6
6
  import type { EnrolledCredential, EnrollmentChallenge, EnrollmentProof, MfaCredentialType, StepUpChallenge, StepUpProof } from './authentication-jwt-bearer/mfa/types.js';
7
7
  import type { PairProfilesResponse } from './authentication-jwt-bearer/services.js';
8
- import type { AccessToken, UserProfile, Pair, PairSocialIdentifierParams, OidcTokenAudience, OidcTokenClaims, UserProfileLineage } from './authentication-jwt-bearer/types.js';
8
+ import type { AccessToken, UserProfile, Pair, PairSocialIdentifierParams, ProfileIdentifier, OidcTokenAudience, OidcTokenClaims, UserProfileLineage } from './authentication-jwt-bearer/types.js';
9
9
  type SIWEInterface = PublicInterface<SIWEJwtBearerAuth>;
10
10
  export type SRPInterface = PublicInterface<SRPJwtBearerAuth>;
11
11
  type SiweParams = ConstructorParameters<typeof SIWEJwtBearerAuth>;
@@ -34,7 +34,7 @@ export declare class JwtBearerAuth implements SIWEInterface, SRPInterface {
34
34
  getMfaCredentials(entropySourceId?: string): Promise<EnrolledCredential[]>;
35
35
  exchangeMfaAssertion(assertionJwt: string): Promise<AccessToken>;
36
36
  pairSrpProfiles(accessTokens: string[], authAccessToken: string): Promise<PairProfilesResponse>;
37
- pairSocialIdentifier(params: PairSocialIdentifierParams, authAccessToken: string): Promise<void>;
37
+ pairSocialIdentifier(params: PairSocialIdentifierParams, authAccessToken: string): Promise<ProfileIdentifier[] | undefined>;
38
38
  signMessage(message: string, entropySourceId?: string): Promise<string>;
39
39
  pairIdentifiers(pairing: Pair[]): Promise<void>;
40
40
  prepare(signer: {
@@ -1 +1 @@
1
- {"version":3,"file":"authentication.d.ts","sourceRoot":"","sources":["../../src/sdk/authentication.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAG9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,yCAAyC,CAAC;AAC3E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6CAA6C,CAAC;AACtF,OAAO,KAAK,EACV,kBAAkB,EAClB,mBAAmB,EACnB,eAAe,EACf,iBAAiB,EACjB,eAAe,EACf,WAAW,EACZ,MAAM,0CAA0C,CAAC;AAKlD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,KAAK,EACV,WAAW,EACX,WAAW,EACX,IAAI,EACJ,0BAA0B,EAC1B,iBAAiB,EACjB,eAAe,EACf,kBAAkB,EACnB,MAAM,sCAAsC,CAAC;AAM9C,KAAK,aAAa,GAAG,eAAe,CAAC,iBAAiB,CAAC,CAAC;AACxD,MAAM,MAAM,YAAY,GAAG,eAAe,CAAC,gBAAgB,CAAC,CAAC;AAE7D,KAAK,UAAU,GAAG,qBAAqB,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAClE,KAAK,SAAS,GAAG,qBAAqB,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAChE,KAAK,mBAAmB,GAAG,UAAU,GAAG,SAAS,CAAC;AAElD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EAClC,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,iBAAiB,EAAE,GAAG,SAAS,CAAC,CAG1C;IAEK,WAAW,CACf,OAAO,EAAE,MAAM,EACf,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,CAAC,CAEjB;IAEK,eAAe,CAAC,OAAO,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CA4BpD;IAED,OAAO,CAAC,MAAM,EAAE;QACd,OAAO,EAAE,MAAM,CAAC;QAChB,OAAO,EAAE,MAAM,CAAC;QAChB,WAAW,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;QAClD,MAAM,EAAE,MAAM,CAAC;KAChB,GAAG,IAAI,CAGP;CA2BF;AAED,OAAO,EAAE,iBAAiB,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,yCAAyC,CAAC;AAC3E,cAAc,sCAAsC,CAAC"}
@@ -80,7 +80,7 @@ export class JwtBearerAuth {
80
80
  }
81
81
  async pairSocialIdentifier(params, authAccessToken) {
82
82
  this.#assertSRP(this.#type, this.#sdk);
83
- await this.#sdk.pairSocialIdentifier(params, authAccessToken);
83
+ return await this.#sdk.pairSocialIdentifier(params, authAccessToken);
84
84
  }
85
85
  async signMessage(message, entropySourceId) {
86
86
  return await this.#sdk.signMessage(message, entropySourceId);
@@ -1 +1 @@
1
- {"version":3,"file":"authentication.js","sourceRoot":"","sources":["../../src/sdk/authentication.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,iBAAiB,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,yCAAyC,CAAC;AAU3E,OAAO,EACL,QAAQ,EACR,eAAe,GAChB,MAAM,yCAAyC,CAAC;AAWjD,OAAO,EAAE,QAAQ,EAAE,MAAM,sCAAsC,CAAC;AAChE,OAAO,EAAE,SAAS,EAAE,wBAAwB,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AAC,CAAC,IAAI,EAAE,CAAC,CAAC;gBAC3D,MAAM,IAAI,SAAS,CACjB,mCAAmC,YAAY,EAAE,CAClD,CAAC;YACJ,CAAC;QACH,CAAC,CAAC,CACH,CAAC;QAEF,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,cAAc,EAAE,CAAC;QAChD,MAAM,eAAe,CAAC,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;IACjE,CAAC;IAED,OAAO,CAAC,MAKP;QACC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QACxC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAC5B,CAAC;IAED,WAAW,CACT,IAAc,EACd,IAA0C;QAE1C,IAAI,IAAI,KAAK,QAAQ,CAAC,IAAI,EAAE,CAAC;YAC3B,OAAO;QACT,CAAC;QAED,MAAM,IAAI,wBAAwB,CAChC,kDAAkD,CACnD,CAAC;IACJ,CAAC;IAED,UAAU,CACR,IAAc,EACd,IAA0C;QAE1C,IAAI,IAAI,KAAK,QAAQ,CAAC,GAAG,EAAE,CAAC;YAC1B,OAAO;QACT,CAAC;QAED,MAAM,IAAI,wBAAwB,CAChC,iDAAiD,CAClD,CAAC;IACJ,CAAC;CACF;AAED,OAAO,EAAE,iBAAiB,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,yCAAyC,CAAC;AAC3E,cAAc,sCAAsC,CAAC","sourcesContent":["import type { PublicInterface } from '@metamask/utils';\nimport type { Eip1193Provider } from 'ethers';\n\nimport type { Env } from '../shared/env.js';\nimport { SIWEJwtBearerAuth } from './authentication-jwt-bearer/flow-siwe.js';\nimport { SRPJwtBearerAuth } from './authentication-jwt-bearer/flow-srp.js';\nimport type { MfaStepUpAssertion } from './authentication-jwt-bearer/mfa/services.js';\nimport type {\n EnrolledCredential,\n EnrollmentChallenge,\n EnrollmentProof,\n MfaCredentialType,\n StepUpChallenge,\n StepUpProof,\n} from './authentication-jwt-bearer/mfa/types.js';\nimport {\n getNonce,\n pairIdentifiers,\n} from './authentication-jwt-bearer/services.js';\nimport type { PairProfilesResponse } from './authentication-jwt-bearer/services.js';\nimport type {\n AccessToken,\n UserProfile,\n Pair,\n PairSocialIdentifierParams,\n OidcTokenAudience,\n OidcTokenClaims,\n UserProfileLineage,\n} from './authentication-jwt-bearer/types.js';\nimport { AuthType } from './authentication-jwt-bearer/types.js';\nimport { PairError, UnsupportedAuthTypeError } from './errors.js';\n\n// Computing the Classes, so we only get back the public methods for the interface.\n\ntype SIWEInterface = PublicInterface<SIWEJwtBearerAuth>;\nexport type SRPInterface = PublicInterface<SRPJwtBearerAuth>;\n\ntype SiweParams = ConstructorParameters<typeof SIWEJwtBearerAuth>;\ntype SRPParams = ConstructorParameters<typeof SRPJwtBearerAuth>;\ntype JwtBearerAuthParams = SiweParams | SRPParams;\n\nexport class JwtBearerAuth implements SIWEInterface, SRPInterface {\n readonly #type: AuthType;\n\n readonly #env: Env;\n\n readonly #sdk: SIWEJwtBearerAuth | SRPJwtBearerAuth;\n\n constructor(...args: JwtBearerAuthParams) {\n this.#type = args[0].type;\n this.#env = args[0].env;\n\n if (args[0].type === AuthType.SRP) {\n this.#sdk = new SRPJwtBearerAuth(args[0], args[1]);\n return;\n }\n\n if (args[0].type === AuthType.SiWE) {\n this.#sdk = new SIWEJwtBearerAuth(args[0], args[1]);\n return;\n }\n\n throw new UnsupportedAuthTypeError('unsupported auth type');\n }\n\n setCustomProvider(provider: Eip1193Provider) {\n this.#assertSRP(this.#type, this.#sdk);\n this.#sdk.setCustomProvider(provider);\n }\n\n async getAccessToken(entropySourceId?: string): Promise<string> {\n return await this.#sdk.getAccessToken(entropySourceId);\n }\n\n async connectSnap(): Promise<string> {\n this.#assertSRP(this.#type, this.#sdk);\n return this.#sdk.connectSnap();\n }\n\n async isSnapConnected(): Promise<boolean> {\n this.#assertSRP(this.#type, this.#sdk);\n return this.#sdk.isSnapConnected();\n }\n\n async getUserProfile(entropySourceId?: string): Promise<UserProfile> {\n return await this.#sdk.getUserProfile(entropySourceId);\n }\n\n async getIdentifier(entropySourceId?: string): Promise<string> {\n return await this.#sdk.getIdentifier(entropySourceId);\n }\n\n async getUserProfileLineage(\n entropySourceId?: string,\n ): Promise<UserProfileLineage> {\n return await this.#sdk.getUserProfileLineage(entropySourceId);\n }\n\n async getCustomerServiceToken(entropySourceId?: string): Promise<string> {\n return await this.#sdk.getCustomerServiceToken(entropySourceId);\n }\n\n async getPartnerIdentityToken(\n claims: OidcTokenClaims,\n audience: OidcTokenAudience,\n entropySourceId?: string,\n ): Promise<string> {\n return await this.#sdk.getPartnerIdentityToken(\n claims,\n audience,\n entropySourceId,\n );\n }\n\n async beginMfaEnrollment(\n type: MfaCredentialType,\n options?: {\n email?: string;\n entropySourceId?: string;\n accessToken?: string;\n },\n ): Promise<EnrollmentChallenge> {\n this.#assertSRP(this.#type, this.#sdk);\n return await this.#sdk.beginMfaEnrollment(type, options);\n }\n\n async completeMfaEnrollment(\n flowId: string,\n proof: EnrollmentProof,\n entropySourceId?: string,\n ): Promise<void> {\n this.#assertSRP(this.#type, this.#sdk);\n await this.#sdk.completeMfaEnrollment(flowId, proof, entropySourceId);\n }\n\n async beginMfaVerification(\n type: MfaCredentialType,\n entropySourceId?: string,\n ): Promise<StepUpChallenge> {\n this.#assertSRP(this.#type, this.#sdk);\n return await this.#sdk.beginMfaVerification(type, entropySourceId);\n }\n\n async completeMfaVerification(\n flowId: string,\n proof: StepUpProof,\n entropySourceId?: string,\n ): Promise<MfaStepUpAssertion> {\n this.#assertSRP(this.#type, this.#sdk);\n return await this.#sdk.completeMfaVerification(\n flowId,\n proof,\n entropySourceId,\n );\n }\n\n async getMfaCredentials(\n entropySourceId?: string,\n ): Promise<EnrolledCredential[]> {\n this.#assertSRP(this.#type, this.#sdk);\n return await this.#sdk.getMfaCredentials(entropySourceId);\n }\n\n async exchangeMfaAssertion(assertionJwt: string): Promise<AccessToken> {\n this.#assertSRP(this.#type, this.#sdk);\n return await this.#sdk.exchangeMfaAssertion(assertionJwt);\n }\n\n async pairSrpProfiles(\n accessTokens: string[],\n authAccessToken: string,\n ): Promise<PairProfilesResponse> {\n this.#assertSRP(this.#type, this.#sdk);\n return await this.#sdk.pairSrpProfiles(accessTokens, authAccessToken);\n }\n\n async pairSocialIdentifier(\n params: PairSocialIdentifierParams,\n authAccessToken: string,\n ): Promise<void> {\n this.#assertSRP(this.#type, this.#sdk);\n await this.#sdk.pairSocialIdentifier(params, authAccessToken);\n }\n\n async signMessage(\n message: string,\n entropySourceId?: string,\n ): Promise<string> {\n return await this.#sdk.signMessage(message, entropySourceId);\n }\n\n async pairIdentifiers(pairing: Pair[]): Promise<void> {\n const profile = await this.getUserProfile();\n const n = await getNonce(profile.profileId, this.#env);\n\n const logins = await Promise.all(\n pairing.map(async (p) => {\n try {\n const raw = `metamask:${n.nonce}:${p.identifier}`;\n const sig = await p.signMessage(raw);\n return {\n signature: sig,\n raw_message: raw,\n encrypted_storage_key: p.encryptedStorageKey,\n identifier_type: p.identifierType,\n };\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new PairError(\n `failed to sign pairing message: ${errorMessage}`,\n );\n }\n }),\n );\n\n const accessToken = await this.getAccessToken();\n await pairIdentifiers(n.nonce, logins, accessToken, this.#env);\n }\n\n prepare(signer: {\n address: string;\n chainId: number;\n signMessage: (message: string) => Promise<string>;\n domain: string;\n }): void {\n this.#assertSIWE(this.#type, this.#sdk);\n this.#sdk.prepare(signer);\n }\n\n #assertSIWE(\n type: AuthType,\n _sdk: SIWEJwtBearerAuth | SRPJwtBearerAuth,\n ): asserts _sdk is SIWEJwtBearerAuth {\n if (type === AuthType.SiWE) {\n return;\n }\n\n throw new UnsupportedAuthTypeError(\n 'This method is only available via SIWE auth type',\n );\n }\n\n #assertSRP(\n type: AuthType,\n _sdk: SIWEJwtBearerAuth | SRPJwtBearerAuth,\n ): asserts _sdk is SRPJwtBearerAuth {\n if (type === AuthType.SRP) {\n return;\n }\n\n throw new UnsupportedAuthTypeError(\n 'This method is only available via SRP auth type',\n );\n }\n}\n\nexport { SIWEJwtBearerAuth } from './authentication-jwt-bearer/flow-siwe.js';\nexport { SRPJwtBearerAuth } from './authentication-jwt-bearer/flow-srp.js';\nexport * from './authentication-jwt-bearer/types.js';\n"]}
1
+ {"version":3,"file":"authentication.js","sourceRoot":"","sources":["../../src/sdk/authentication.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,iBAAiB,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,yCAAyC,CAAC;AAU3E,OAAO,EACL,QAAQ,EACR,eAAe,GAChB,MAAM,yCAAyC,CAAC;AAYjD,OAAO,EAAE,QAAQ,EAAE,MAAM,sCAAsC,CAAC;AAChE,OAAO,EAAE,SAAS,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAWlE,MAAM,OAAO,aAAa;IACf,KAAK,CAAW;IAEhB,IAAI,CAAM;IAEV,IAAI,CAAuC;IAEpD,YAAY,GAAG,IAAyB;QACtC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;QAExB,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,GAAG,EAAE,CAAC;YAClC,IAAI,CAAC,IAAI,GAAG,IAAI,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;YACnD,OAAO;QACT,CAAC;QAED,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,EAAE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AAE,CAAC;YAC3B,OAAO;QACT,CAAC;QAED,MAAM,IAAI,wBAAwB,CAChC,kDAAkD,CACnD,CAAC;IACJ,CAAC;IAED,UAAU,CACR,IAAc,EACd,IAA0C;QAE1C,IAAI,IAAI,KAAK,QAAQ,CAAC,GAAG,EAAE,CAAC;YAC1B,OAAO;QACT,CAAC;QAED,MAAM,IAAI,wBAAwB,CAChC,iDAAiD,CAClD,CAAC;IACJ,CAAC;CACF;AAED,OAAO,EAAE,iBAAiB,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,yCAAyC,CAAC;AAC3E,cAAc,sCAAsC,CAAC","sourcesContent":["import type { PublicInterface } from '@metamask/utils';\nimport type { Eip1193Provider } from 'ethers';\n\nimport type { Env } from '../shared/env.js';\nimport { SIWEJwtBearerAuth } from './authentication-jwt-bearer/flow-siwe.js';\nimport { SRPJwtBearerAuth } from './authentication-jwt-bearer/flow-srp.js';\nimport type { MfaStepUpAssertion } from './authentication-jwt-bearer/mfa/services.js';\nimport type {\n EnrolledCredential,\n EnrollmentChallenge,\n EnrollmentProof,\n MfaCredentialType,\n StepUpChallenge,\n StepUpProof,\n} from './authentication-jwt-bearer/mfa/types.js';\nimport {\n getNonce,\n pairIdentifiers,\n} from './authentication-jwt-bearer/services.js';\nimport type { PairProfilesResponse } from './authentication-jwt-bearer/services.js';\nimport type {\n AccessToken,\n UserProfile,\n Pair,\n PairSocialIdentifierParams,\n ProfileIdentifier,\n OidcTokenAudience,\n OidcTokenClaims,\n UserProfileLineage,\n} from './authentication-jwt-bearer/types.js';\nimport { AuthType } from './authentication-jwt-bearer/types.js';\nimport { PairError, UnsupportedAuthTypeError } from './errors.js';\n\n// Computing the Classes, so we only get back the public methods for the interface.\n\ntype SIWEInterface = PublicInterface<SIWEJwtBearerAuth>;\nexport type SRPInterface = PublicInterface<SRPJwtBearerAuth>;\n\ntype SiweParams = ConstructorParameters<typeof SIWEJwtBearerAuth>;\ntype SRPParams = ConstructorParameters<typeof SRPJwtBearerAuth>;\ntype JwtBearerAuthParams = SiweParams | SRPParams;\n\nexport class JwtBearerAuth implements SIWEInterface, SRPInterface {\n readonly #type: AuthType;\n\n readonly #env: Env;\n\n readonly #sdk: SIWEJwtBearerAuth | SRPJwtBearerAuth;\n\n constructor(...args: JwtBearerAuthParams) {\n this.#type = args[0].type;\n this.#env = args[0].env;\n\n if (args[0].type === AuthType.SRP) {\n this.#sdk = new SRPJwtBearerAuth(args[0], args[1]);\n return;\n }\n\n if (args[0].type === AuthType.SiWE) {\n this.#sdk = new SIWEJwtBearerAuth(args[0], args[1]);\n return;\n }\n\n throw new UnsupportedAuthTypeError('unsupported auth type');\n }\n\n setCustomProvider(provider: Eip1193Provider) {\n this.#assertSRP(this.#type, this.#sdk);\n this.#sdk.setCustomProvider(provider);\n }\n\n async getAccessToken(entropySourceId?: string): Promise<string> {\n return await this.#sdk.getAccessToken(entropySourceId);\n }\n\n async connectSnap(): Promise<string> {\n this.#assertSRP(this.#type, this.#sdk);\n return this.#sdk.connectSnap();\n }\n\n async isSnapConnected(): Promise<boolean> {\n this.#assertSRP(this.#type, this.#sdk);\n return this.#sdk.isSnapConnected();\n }\n\n async getUserProfile(entropySourceId?: string): Promise<UserProfile> {\n return await this.#sdk.getUserProfile(entropySourceId);\n }\n\n async getIdentifier(entropySourceId?: string): Promise<string> {\n return await this.#sdk.getIdentifier(entropySourceId);\n }\n\n async getUserProfileLineage(\n entropySourceId?: string,\n ): Promise<UserProfileLineage> {\n return await this.#sdk.getUserProfileLineage(entropySourceId);\n }\n\n async getCustomerServiceToken(entropySourceId?: string): Promise<string> {\n return await this.#sdk.getCustomerServiceToken(entropySourceId);\n }\n\n async getPartnerIdentityToken(\n claims: OidcTokenClaims,\n audience: OidcTokenAudience,\n entropySourceId?: string,\n ): Promise<string> {\n return await this.#sdk.getPartnerIdentityToken(\n claims,\n audience,\n entropySourceId,\n );\n }\n\n async beginMfaEnrollment(\n type: MfaCredentialType,\n options?: {\n email?: string;\n entropySourceId?: string;\n accessToken?: string;\n },\n ): Promise<EnrollmentChallenge> {\n this.#assertSRP(this.#type, this.#sdk);\n return await this.#sdk.beginMfaEnrollment(type, options);\n }\n\n async completeMfaEnrollment(\n flowId: string,\n proof: EnrollmentProof,\n entropySourceId?: string,\n ): Promise<void> {\n this.#assertSRP(this.#type, this.#sdk);\n await this.#sdk.completeMfaEnrollment(flowId, proof, entropySourceId);\n }\n\n async beginMfaVerification(\n type: MfaCredentialType,\n entropySourceId?: string,\n ): Promise<StepUpChallenge> {\n this.#assertSRP(this.#type, this.#sdk);\n return await this.#sdk.beginMfaVerification(type, entropySourceId);\n }\n\n async completeMfaVerification(\n flowId: string,\n proof: StepUpProof,\n entropySourceId?: string,\n ): Promise<MfaStepUpAssertion> {\n this.#assertSRP(this.#type, this.#sdk);\n return await this.#sdk.completeMfaVerification(\n flowId,\n proof,\n entropySourceId,\n );\n }\n\n async getMfaCredentials(\n entropySourceId?: string,\n ): Promise<EnrolledCredential[]> {\n this.#assertSRP(this.#type, this.#sdk);\n return await this.#sdk.getMfaCredentials(entropySourceId);\n }\n\n async exchangeMfaAssertion(assertionJwt: string): Promise<AccessToken> {\n this.#assertSRP(this.#type, this.#sdk);\n return await this.#sdk.exchangeMfaAssertion(assertionJwt);\n }\n\n async pairSrpProfiles(\n accessTokens: string[],\n authAccessToken: string,\n ): Promise<PairProfilesResponse> {\n this.#assertSRP(this.#type, this.#sdk);\n return await this.#sdk.pairSrpProfiles(accessTokens, authAccessToken);\n }\n\n async pairSocialIdentifier(\n params: PairSocialIdentifierParams,\n authAccessToken: string,\n ): Promise<ProfileIdentifier[] | undefined> {\n this.#assertSRP(this.#type, this.#sdk);\n return await this.#sdk.pairSocialIdentifier(params, authAccessToken);\n }\n\n async signMessage(\n message: string,\n entropySourceId?: string,\n ): Promise<string> {\n return await this.#sdk.signMessage(message, entropySourceId);\n }\n\n async pairIdentifiers(pairing: Pair[]): Promise<void> {\n const profile = await this.getUserProfile();\n const n = await getNonce(profile.profileId, this.#env);\n\n const logins = await Promise.all(\n pairing.map(async (p) => {\n try {\n const raw = `metamask:${n.nonce}:${p.identifier}`;\n const sig = await p.signMessage(raw);\n return {\n signature: sig,\n raw_message: raw,\n encrypted_storage_key: p.encryptedStorageKey,\n identifier_type: p.identifierType,\n };\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new PairError(\n `failed to sign pairing message: ${errorMessage}`,\n );\n }\n }),\n );\n\n const accessToken = await this.getAccessToken();\n await pairIdentifiers(n.nonce, logins, accessToken, this.#env);\n }\n\n prepare(signer: {\n address: string;\n chainId: number;\n signMessage: (message: string) => Promise<string>;\n domain: string;\n }): void {\n this.#assertSIWE(this.#type, this.#sdk);\n this.#sdk.prepare(signer);\n }\n\n #assertSIWE(\n type: AuthType,\n _sdk: SIWEJwtBearerAuth | SRPJwtBearerAuth,\n ): asserts _sdk is SIWEJwtBearerAuth {\n if (type === AuthType.SiWE) {\n return;\n }\n\n throw new UnsupportedAuthTypeError(\n 'This method is only available via SIWE auth type',\n );\n }\n\n #assertSRP(\n type: AuthType,\n _sdk: SIWEJwtBearerAuth | SRPJwtBearerAuth,\n ): asserts _sdk is SRPJwtBearerAuth {\n if (type === AuthType.SRP) {\n return;\n }\n\n throw new UnsupportedAuthTypeError(\n 'This method is only available via SRP auth type',\n );\n }\n}\n\nexport { SIWEJwtBearerAuth } from './authentication-jwt-bearer/flow-siwe.js';\nexport { SRPJwtBearerAuth } from './authentication-jwt-bearer/flow-srp.js';\nexport * from './authentication-jwt-bearer/types.js';\n"]}
@@ -11,6 +11,10 @@ export type RawPairResponse = {
11
11
  profile_id: string;
12
12
  identifier_id: string;
13
13
  metametrics_id?: string;
14
+ paired_identifier_ids?: {
15
+ id: string;
16
+ type: string;
17
+ }[];
14
18
  };
15
19
  profile_aliases?: RawProfileAlias[];
16
20
  };
@@ -1 +1 @@
1
- {"version":3,"file":"validate-pair-response.d.ts","sourceRoot":"","sources":["../../../src/sdk/utils/validate-pair-response.ts"],"names":[],"mappings":"AAEA,KAAK,eAAe,GAAG;IACrB,gBAAgB,EAAE,MAAM,CAAC;IACzB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,cAAc,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CAChD,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,OAAO,EAAE;QACP,UAAU,EAAE,MAAM,CAAC;QACnB,aAAa,EAAE,MAAM,CAAC;QACtB,cAAc,CAAC,EAAE,MAAM,CAAC;KACzB,CAAC;IACF,eAAe,CAAC,EAAE,eAAe,EAAE,CAAC;CACrC,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,KAAK,IAAI,eAAe,CAwBlC"}
1
+ {"version":3,"file":"validate-pair-response.d.ts","sourceRoot":"","sources":["../../../src/sdk/utils/validate-pair-response.ts"],"names":[],"mappings":"AAEA,KAAK,eAAe,GAAG;IACrB,gBAAgB,EAAE,MAAM,CAAC;IACzB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,cAAc,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CAChD,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,OAAO,EAAE;QACP,UAAU,EAAE,MAAM,CAAC;QACnB,aAAa,EAAE,MAAM,CAAC;QACtB,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,qBAAqB,CAAC,EAAE;YAAE,EAAE,EAAE,MAAM,CAAC;YAAC,IAAI,EAAE,MAAM,CAAA;SAAE,EAAE,CAAC;KACxD,CAAC;IACF,eAAe,CAAC,EAAE,eAAe,EAAE,CAAC;CACrC,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,KAAK,IAAI,eAAe,CAwBlC"}
@@ -1 +1 @@
1
- {"version":3,"file":"validate-pair-response.js","sourceRoot":"","sources":["../../../src/sdk/utils/validate-pair-response.ts"],"names":[],"mappings":"AAAA,yDAAyD;AAiBzD;;;;;;GAMG;AACH,MAAM,UAAU,oBAAoB,CAClC,KAAc;IAEd,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACxC,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;IAClE,CAAC;IAED,MAAM,OAAO,GAAG,KAAgC,CAAC;IACjD,MAAM,OAAO,GAAG,OAAO,CAAC,OAA8C,CAAC;IACvE,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAC5C,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAC;IACJ,CAAC;IAED,IAAI,OAAO,OAAO,CAAC,UAAU,KAAK,QAAQ,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;QAClE,MAAM,IAAI,KAAK,CACb,8DAA8D,CAC/D,CAAC;IACJ,CAAC;IAED,IAAI,OAAO,OAAO,CAAC,aAAa,KAAK,QAAQ,IAAI,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC;QACxE,MAAM,IAAI,KAAK,CACb,iEAAiE,CAClE,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/naming-convention */\n\ntype RawProfileAlias = {\n alias_profile_id: string;\n canonical_profile_id: string;\n identifier_ids: { id: string; type: string }[];\n};\n\nexport type RawPairResponse = {\n profile: {\n profile_id: string;\n identifier_id: string;\n metametrics_id?: string;\n };\n profile_aliases?: RawProfileAlias[];\n};\n\n/**\n * Asserts that the raw API response from the profile pairing endpoint has the\n * expected shape before we attempt to map it into a `PairProfilesResponse`.\n * Throws if the response is malformed.\n *\n * @param input - The raw JSON parsed from the pair endpoint response body.\n */\nexport function validatePairResponse(\n input: unknown,\n): asserts input is RawPairResponse {\n if (!input || typeof input !== 'object') {\n throw new Error('validatePairResponse: input is not an object');\n }\n\n const assumed = input as Record<string, unknown>;\n const profile = assumed.profile as Record<string, unknown> | undefined;\n if (!profile || typeof profile !== 'object') {\n throw new Error(\n 'validatePairResponse: profile is missing or not an object',\n );\n }\n\n if (typeof profile.profile_id !== 'string' || !profile.profile_id) {\n throw new Error(\n 'validatePairResponse: profile.profile_id is missing or empty',\n );\n }\n\n if (typeof profile.identifier_id !== 'string' || !profile.identifier_id) {\n throw new Error(\n 'validatePairResponse: profile.identifier_id is missing or empty',\n );\n }\n}\n"]}
1
+ {"version":3,"file":"validate-pair-response.js","sourceRoot":"","sources":["../../../src/sdk/utils/validate-pair-response.ts"],"names":[],"mappings":"AAAA,yDAAyD;AAkBzD;;;;;;GAMG;AACH,MAAM,UAAU,oBAAoB,CAClC,KAAc;IAEd,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACxC,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;IAClE,CAAC;IAED,MAAM,OAAO,GAAG,KAAgC,CAAC;IACjD,MAAM,OAAO,GAAG,OAAO,CAAC,OAA8C,CAAC;IACvE,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAC5C,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAC;IACJ,CAAC;IAED,IAAI,OAAO,OAAO,CAAC,UAAU,KAAK,QAAQ,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;QAClE,MAAM,IAAI,KAAK,CACb,8DAA8D,CAC/D,CAAC;IACJ,CAAC;IAED,IAAI,OAAO,OAAO,CAAC,aAAa,KAAK,QAAQ,IAAI,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC;QACxE,MAAM,IAAI,KAAK,CACb,iEAAiE,CAClE,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/naming-convention */\n\ntype RawProfileAlias = {\n alias_profile_id: string;\n canonical_profile_id: string;\n identifier_ids: { id: string; type: string }[];\n};\n\nexport type RawPairResponse = {\n profile: {\n profile_id: string;\n identifier_id: string;\n metametrics_id?: string;\n paired_identifier_ids?: { id: string; type: string }[];\n };\n profile_aliases?: RawProfileAlias[];\n};\n\n/**\n * Asserts that the raw API response from the profile pairing endpoint has the\n * expected shape before we attempt to map it into a `PairProfilesResponse`.\n * Throws if the response is malformed.\n *\n * @param input - The raw JSON parsed from the pair endpoint response body.\n */\nexport function validatePairResponse(\n input: unknown,\n): asserts input is RawPairResponse {\n if (!input || typeof input !== 'object') {\n throw new Error('validatePairResponse: input is not an object');\n }\n\n const assumed = input as Record<string, unknown>;\n const profile = assumed.profile as Record<string, unknown> | undefined;\n if (!profile || typeof profile !== 'object') {\n throw new Error(\n 'validatePairResponse: profile is missing or not an object',\n );\n }\n\n if (typeof profile.profile_id !== 'string' || !profile.profile_id) {\n throw new Error(\n 'validatePairResponse: profile.profile_id is missing or empty',\n );\n }\n\n if (typeof profile.identifier_id !== 'string' || !profile.identifier_id) {\n throw new Error(\n 'validatePairResponse: profile.identifier_id is missing or empty',\n );\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/profile-sync-controller",
3
- "version": "32.2.0-preview-f61294996",
3
+ "version": "32.2.0-preview-8b8e439a2",
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",