FirefoxAccountProtocol

public protocol FirefoxAccountProtocol : AnyObject

Object representing the signed-in state of an application.

The FirefoxAccount object is the main interface provided by this crate. It represents the signed-in state of an application that may be connected to user’s Firefox Account, and provides methods for inspecting the state of the account and accessing other services on behalf of the user.

  • Create a new OAuth authorization code using the stored session token.

    When a signed-in application receives an incoming device pairing request, it can use this method to grant the request and generate a corresponding OAuth authorization code. This code would then be passed back to the connecting device over the pairing channel (a process which is not currently supported by any code in this component).

    # Arguments

    - `params` - the OAuth parameters from the incoming authorization request
    

    Declaration

    Swift

    func authorizeCodeUsingSessionToken(params: AuthorizationParameters) throws -> String
  • Initiate a web-based OAuth sign-in flow.

    This method initializes some internal state and then returns a URL at which the user may perform a web-based authorization flow to connect the application to their account. The application should direct the user to the provided URL.

    When the resulting OAuth flow redirects back to the configured redirect_uri, the query parameters should be extracting from the URL and passed to the complete_oauth_flow method to finalize the signin.

    # Arguments

    • scopes - list of OAuth scopes to request.
      • The requested scopes will determine what account-related data the application is able to access.
    • entrypoint - metrics identifier for UX entrypoint.
      • This parameter is used for metrics purposes, to identify the UX entrypoint from which the user triggered the signin request. For example, the application toolbar, on the onboarding flow.
    • metrics - optionally, additional metrics tracking parameters.
      • These will be included as query parameters in the resulting URL.

    Declaration

    Swift

    func beginOauthFlow(scopes: [String], entrypoint: String) throws -> String
  • Initiate a device-pairing sign-in flow.

    Once the user has scanned a pairing QR code, pass the scanned value to this method. It will return a URL to which the application should redirect the user in order to continue the sign-in flow.

    When the resulting flow redirects back to the configured redirect_uri, the resulting OAuth parameters should be extracting from the URL and passed to complete_oauth_flow to finalize the signin.

    # Arguments

    • pairing_url - the URL scanned from a QR code on another device.
    • scopes - list of OAuth scopes to request.
      • The requested scopes will determine what account-related data the application is able to access.
    • entrypoint - metrics identifier for UX entrypoint.
      • This parameter is used for metrics purposes, to identify the UX entrypoint from which the user triggered the signin request. For example, the application toolbar, on the onboarding flow.
    • metrics - optionally, additional metrics tracking parameters.
      • These will be included as query parameters in the resulting URL.

    Declaration

    Swift

    func beginPairingFlow(pairingUrl: String, scopes: [String], entrypoint: String) throws -> String
  • Check authorization status for this application.

    💾 This method alters the persisted account state.

    Applications may call this method to check with the FxA server about the status of their authentication tokens. It returns an [AuthorizationInfo] struct with details about whether the tokens are still active.

    Declaration

    Swift

    func checkAuthorizationStatus() throws -> AuthorizationInfo
  • Clear the access token cache in response to an auth failure.

    💾 This method alters the persisted account state.

    Applications that receive an authentication error when trying to use an access token, should call this method before creating a new token and retrying the failed operation. It ensures that the expired token is removed and a fresh one generated.

    Declaration

    Swift

    func clearAccessTokenCache()
  • Clear any custom display name used for this application instance.

    💾 This method alters the persisted account state.

    This method clears the name of the current application’s device record, causing other applications or the user’s account management pages to have to fill in some sort of default name when displaying this device.

    # Notes

    - Device registration is only available to applications that have been
      granted the `https:///identity.mozilla.com/apps/oldsync` scope.
    

    Declaration

    Swift

    func clearDeviceName() throws
  • Use device commands to close one or more tabs on another device.

    💾 This method alters the persisted account state.

    If a device on the account has registered the CloseTabs capability, this method can be used to close its tabs.

    Declaration

    Swift

    func closeTabs(targetDeviceId: String, urls: [String]) throws -> CloseTabsResult
  • Complete an OAuth flow.

    💾 This method alters the persisted account state.

    At the conclusion of an OAuth flow, the user will be redirect to the application’s registered redirect_uri. It should extract the code and state parameters from the resulting URL and pass them to this method in order to complete the sign-in.

    # Arguments

    • code - the OAuth authorization code obtained from the redirect URI.
    • state - the OAuth state parameter obtained from the redirect URI.

    Declaration

    Swift

    func completeOauthFlow(code: String, state: String) throws
  • Disconnect from the user’s account.

    💾 This method alters the persisted account state.

    This method destroys any tokens held by the client, effectively disconnecting from the user’s account. Applications should call this when the user opts to sign out.

    The persisted account state after calling this method will contain only the user’s last-seen profile information, if any. This may be useful in helping the user to reconnnect to their account. If reconnecting to the same account is not desired then the application should discard the persisted account state.

    Declaration

    Swift

    func disconnect()
  • Ensure that the device record has a specific set of capabilities.

    💾 This method alters the persisted account state.

    This method checks that the currently-registered device record is advertising the given set of capabilities in the FxA “device commands” ecosystem. If not, then it updates the device record to do so.

    Applications should call this method on each startup as a way to ensure that their expected set of capabilities is being accurately reflected on the FxA server, and to handle the rollout of new capabilities over time.

    # Arguments

    - `supported_capabilities` - the set of [capabilities](DeviceCapability) to register
       for this device in the "device commands" ecosystem.
    

    # Notes

    - Device registration is only available to applications that have been
      granted the `https:///identity.mozilla.com/apps/oldsync` scope.
    

    Declaration

    Swift

    func ensureCapabilities(supportedCapabilities: [DeviceCapability]) throws -> LocalDevice
  • Collect and return telemetry about incoming and outgoing device commands.

    Applications that have registered one or more [DeviceCapability]s should also arrange to submit “sync ping” telemetry. Calling this method will return a JSON string of telemetry data that can be incorporated into that ping.

    Sorry, this is not particularly carefully documented because it is intended as a stop-gap until we get native Glean support. If you know how to submit a sync ping, you’ll know what to do with the contents of the JSON string.

    Declaration

    Swift

    func gatherTelemetry() throws -> String
  • Get a short-lived OAuth access token for the user’s account.

    💾 This method alters the persisted account state.

    Applications that need to access resources on behalf of the user must obtain an access_token in order to do so. For example, an access token is required when fetching the user’s profile data, or when accessing their data stored in Firefox Sync.

    This method will obtain and return an access token bearing the requested scopes, either from a local cache of previously-issued tokens, or by creating a new one from the server.

    # Arguments

    - `scope` - the OAuth scope to be granted by the token.
        - This must be one of the scopes requested during the signin flow.
        - Only a single scope is supported; for multiple scopes request multiple tokens.
    - `ttl` - optionally, the time for which the token should be valid, in seconds.
    

    # Notes

    - If the application receives an authorization error when trying to use the resulting
      token, it should call [`clear_access_token_cache`](FirefoxAccount::clear_access_token_cache)
      before requesting a fresh token.
    

    Declaration

    Swift

    func getAccessToken(scope: String, ttl: Int64?) throws -> AccessTokenInfo
  • Get the list of all client applications attached to the user’s account.

    This method returns a list of [AttachedClient] structs representing all the applications connected to the user’s account. This includes applications that are registered as a device as well as server-side services that the user has connected.

    This information is really only useful for targeted messaging or marketing purposes, e.g. if the application wants to advertize a related product, but first wants to check whether the user is already using that product.

    # Notes

    - Attached client metadata is only visible to applications that have been
      granted the `https:///identity.mozilla.com/apps/oldsync` scope.
    

    Declaration

    Swift

    func getAttachedClients() throws -> [AttachedClient]
  • Get the high-level authentication state of the client

    Deprecated: Use get_state() instead

    Declaration

    Swift

    func getAuthState() -> FxaRustAuthState
  • Get a URL which shows a “successfully connceted!” message.

    💾 This method alters the persisted account state.

    Applications can use this method after a successful signin, to redirect the user to a success message displayed in web content rather than having to implement their own native success UI.

    Declaration

    Swift

    func getConnectionSuccessUrl() throws -> String
  • Get the device id registered for this application.

    # Notes

    - If the application has not registered a device record, this method will
      throw an [`Other`](FxaError::Other) error.
        - (Yeah...sorry. This should be changed to do something better.)
    - Device metadata is only visible to applications that have been
      granted the `https:///identity.mozilla.com/apps/oldsync` scope.
    

    Declaration

    Swift

    func getCurrentDeviceId() throws -> String
  • Get the list of devices registered on the user’s account.

    💾 This method alters the persisted account state.

    This method returns a list of [Device] structs representing all the devices currently attached to the user’s account (including the current device). The application might use this information to e.g. display a list of appropriate send-tab targets.

    # Arguments

    - `ignore_cache` - if true, always hit the server for fresh profile information.
    

    # Notes

    - Device metadata is only visible to applications that have been
      granted the `https:///identity.mozilla.com/apps/oldsync` scope.
    

    Declaration

    Swift

    func getDevices(ignoreCache: Bool) throws -> [Device]
  • Get a URL at which the user can manage their account and profile data.

    💾 This method alters the persisted account state.

    Applications should link the user out to this URL from an appropriate place in their signed-in settings UI.

    # Arguments

    • entrypoint - metrics identifier for UX entrypoint.
      • This parameter is used for metrics purposes, to identify the UX entrypoint from which the user followed the link.

    Declaration

    Swift

    func getManageAccountUrl(entrypoint: String) throws -> String
  • Get a URL at which the user can manage the devices connected to their account.

    💾 This method alters the persisted account state.

    Applications should link the user out to this URL from an appropriate place in their signed-in settings UI. For example, “Manage your devices…” may be a useful link to place somewhere near the device list in the send-tab UI.

    # Arguments

    • entrypoint - metrics identifier for UX entrypoint.
      • This parameter is used for metrics purposes, to identify the UX entrypoint from which the user followed the link.

    Declaration

    Swift

    func getManageDevicesUrl(entrypoint: String) throws -> String
  • Get the URL at which to begin a device-pairing signin flow.

    If the user wants to sign in using device pairing, call this method and then direct them to visit the resulting URL on an already-signed-in device. Doing so will trigger the other device to show a QR code to be scanned, and the result from said QR code can be passed to begin_pairing_flow.

    Declaration

    Swift

    func getPairingAuthorityUrl() throws -> String
  • Get profile information for the signed-in user, if any.

    💾 This method alters the persisted account state.

    This method fetches a [Profile] struct with information about the currently-signed-in user, either by using locally-cached profile information or by fetching fresh data from the server.

    # Arguments

    - `ignore_cache` - if true, always hit the server for fresh profile information.
    

    # Notes

    - Profile information is only available to applications that have been
      granted the `profile` scope.
    - There is currently no API for fetching cached profile information without
      potentially hitting the server.
    - If there is no signed-in user, this method will throw an
      [`Authentication`](FxaError::Authentication) error.
    

    Declaration

    Swift

    func getProfile(ignoreCache: Bool) throws -> Profile
  • Get the session token for the user’s account, if one is available.

    💾 This method alters the persisted account state.

    Applications that function as a web browser may need to hold on to a session token on behalf of Firefox Accounts web content. This method exists so that they can retrieve it an pass it back to said web content when required.

    # Notes

    - Please do not attempt to use the resulting token to directly make calls to the
      Firefox Accounts servers! All account management functionality should be performed
      in web content.
    - A session token is only available to applications that have requested the
      `https:///identity.mozilla.com/tokens/session` scope.
    

    Declaration

    Swift

    func getSessionToken() throws -> String
  • Get the current state

    Declaration

    Swift

    func getState() -> FxaState
  • Get the URL at which to access the user’s sync data.

    💾 This method alters the persisted account state.

    Declaration

    Swift

    func getTokenServerEndpointUrl() throws -> String
  • Process and respond to a server-delivered account update message

    💾 This method alters the persisted account state.

    Applications should call this method whenever they receive a push notification from the Firefox Accounts server. Such messages typically indicate a noteworthy change of state on the user’s account, such as an update to their profile information or the disconnection of a client. The [FirefoxAccount] struct will update its internal state accordingly and return an individual [AccountEvent] struct describing the event, which the application may use for further processing.

    It’s important to note if the event is [AccountEvent::CommandReceived], the caller should call [FirefoxAccount::poll_device_commands]

    Declaration

    Swift

    func handlePushMessage(payload: String) throws -> AccountEvent
  • Update the stored session token for the user’s account.

    💾 This method alters the persisted account state.

    Applications that function as a web browser may need to hold on to a session token on behalf of Firefox Accounts web content. This method exists so that said web content signals that it has generated a new session token, the stored value can be updated to match.

    # Arguments

    - `session_token` - the new session token value provided from web content.
    

    Declaration

    Swift

    func handleSessionTokenChange(sessionToken: String) throws
  • Create a new device record for this application.

    💾 This method alters the persisted account state.

    This method registered a device record for the application, providing basic metadata for the device along with a list of supported Device Capabilities for participating in the “device commands” ecosystem.

    Applications should call this method soon after a successful sign-in, to ensure they they appear correctly in the user’s account-management pages and when discovered by other devices connected to the account.

    # Arguments

    - `name` - human-readable display name to use for this application
    - `device_type` - the [type](DeviceType) of device the application is installed on
    - `supported_capabilities` - the set of [capabilities](DeviceCapability) to register
       for this device in the "device commands" ecosystem.
    

    # Notes

    - Device registration is only available to applications that have been
      granted the `https:///identity.mozilla.com/apps/oldsync` scope.
    

    Declaration

    Swift

    func initializeDevice(name: String, deviceType: DeviceType, supportedCapabilities: [DeviceCapability]) throws -> LocalDevice
  • Update the state based on authentication issues.

    💾 This method alters the persisted account state.

    Call this if you know there’s an authentication / authorization issue that requires the user to re-authenticated. It transitions the user to the [FxaRustAuthState.AuthIssues] state.

    Declaration

    Swift

    func onAuthIssues()
  • Poll the server for any pending device commands.

    💾 This method alters the persisted account state.

    Applications that have registered one or more [DeviceCapability]s with the server can use this method to check whether other devices on the account have sent them any commands. It will return a list of [IncomingDeviceCommand] structs for the application to process.

    # Notes

    - Device commands are typically delivered via push message and the [`CommandReceived`](
      AccountEvent::CommandReceived) event. Polling should only be used as a backup delivery
      mechanism, f the application has reason to believe that push messages may have been missed.
    - Device commands functionality is only available to applications that have been
      granted the `https:///identity.mozilla.com/apps/oldsync` scope.
    

    Declaration

    Swift

    func pollDeviceCommands() throws -> [IncomingDeviceCommand]
  • Process an event (login, logout, etc).

    On success, update the current state and return it. On error, the current state will remain the same.

    Declaration

    Swift

    func processEvent(event: FxaEvent) throws -> FxaState
  • Use device commands to send a single tab to another device.

    💾 This method alters the persisted account state.

    If a device on the account has registered the SendTab capability, this method can be used to send it a tab.

    # Notes

    - If the given device id does not existing or is not capable of receiving tabs,
      this method will throw an [`Other`](FxaError::Other) error.
        - (Yeah...sorry. This should be changed to do something better.)
    - It is not currently possible to send a full [`SendTabPayload`] to another device,
      but that's purely an API limitation that should go away in future.
    - Device commands functionality is only available to applications that have been
      granted the `https:///identity.mozilla.com/apps/oldsync` scope.
    

    Declaration

    Swift

    func sendSingleTab(targetDeviceId: String, title: String, url: String) throws
  • Update the display name used for this application instance.

    💾 This method alters the persisted account state.

    This method modifies the name of the current application’s device record, as seen by other applications and in the user’s account management pages.

    # Arguments

    - `display_name` - the new name for the current device.
    

    # Notes

    - Device registration is only available to applications that have been
      granted the `https:///identity.mozilla.com/apps/oldsync` scope.
    

    Declaration

    Swift

    func setDeviceName(displayName: String) throws -> LocalDevice
  • Set or update a push subscription endpoint for this device.

    💾 This method alters the persisted account state.

    This method registers the given webpush subscription with the FxA server, requesting that is send notifications in the event of any significant changes to the user’s account. When the application receives a push message at the registered subscription endpoint, it should decrypt the payload and pass it to the handle_push_message method for processing.

    # Arguments

    - `subscription` - the [`DevicePushSubscription`] details to register with the server.
    

    # Notes

    - Device registration is only available to applications that have been
      granted the `https:///identity.mozilla.com/apps/oldsync` scope.
    

    Declaration

    Swift

    func setPushSubscription(subscription: DevicePushSubscription) throws -> LocalDevice
  • Sets the users information based on the web content’s login information This is intended to only be used by user agents (eg: Firefox) to set the users session token and tie it to the refresh token that will be issued at the end of the oauth flow.

    Declaration

    Swift

    func setUserData(userData: UserData)
  • Used by the application to test auth token issues

    Declaration

    Swift

    func simulateNetworkError()
  • Used by the application to test auth token issues

    Declaration

    Swift

    func simulatePermanentAuthTokenIssue()
  • Used by the application to test auth token issues

    Declaration

    Swift

    func simulateTemporaryAuthTokenIssue()
  • Save current state to a JSON string.

    This method serializes the current account state into a JSON string, which the application can use to persist the user’s signed-in state across restarts. The application should call this method and update its persisted state after any potentially-state-changing operation.

    ⚠️ Warning: the serialized state may contain encryption keys and access tokens that let anyone holding them access the user’s data in Firefox Sync and/or other FxA services. Applications should take care to store the resulting data in a secure fashion, as appropriate for their target platform.

    Declaration

    Swift

    func toJson() throws -> String