FirefoxAccount
open class FirefoxAccount : FirefoxAccountProtocol, @unchecked Sendable
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 [
FirefoxAccount] instance, not connected to any account.💾 This method alters the persisted account state.
This method constructs as new [
FirefoxAccount] instance configured to connect the application to a user’s account.Declaration
Swift
public convenience init(config: FxaConfig) -
Restore a [
FirefoxAccount] instance from serialized state.Given a JSON string previously obtained from [
FirefoxAccount::to_json], this method will deserialize it and return a live [FirefoxAccount] instance.⚠️ Warning: since the serialized state contains access tokens, you should not call
from_jsonmultiple times on the same data. This would result in multiple live objects sharing the same access tokens and is likely to produce unexpected behaviour.Declaration
Swift
public static func fromJson(data: String) throws -> FirefoxAccount -
Used by the application to test auth token issues
Declaration
Swift
open func simulateNetworkError() -
Get a URL which shows a “successfully connected!” 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
open func getConnectionSuccessUrl() throws -> String -
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
open 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
open func getManageDevicesUrl(entrypoint: String) throws -> String -
Get the token server URL
The token server URL can be used to get the URL and access token for the user’s sync data.
Declaration
Swift
open func getTokenServerEndpointUrl() throws -> String -
Check if an account was created from a config
Declaration
Swift
open func matchesServer(server: FxaServer) throws -> Bool -
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
open func checkAuthorizationStatus() throws -> AuthorizationInfo -
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 reconnect to their account. If reconnecting to the same account is not desired then the application should discard the persisted account state.
Declaration
Swift
open func disconnect() -
Get the high-level authentication state of the client
TODO: remove this and the FxaRustAuthState type from the public API https://bugzilla.mozilla.org/show_bug.cgi?id=1868614
Declaration
Swift
open func getAuthState() -> FxaRustAuthState -
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 the [
FxaEvent::BeginPairingFlow] event.Declaration
Swift
open func getPairingAuthorityUrl() throws -> String -
Get the current state
Declaration
Swift
open func getState() -> FxaState -
Stores the session token from a WebChannel login JSON payload without exposing it to the browser layer.
The
json_payloadis thedataobject from thefxaccounts:loginWebChannel command. The session token is extracted and stored internally; callers never hold the raw token value.💾 This method alters the persisted account state.
Declaration
Swift
open func handleWebChannelLogin(jsonPayload: String) throws -
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
open func onAuthIssues() -
Used by the application to test auth token issues
Declaration
Swift
open func simulatePermanentAuthTokenIssue() -
Used by the application to test auth token issues
Declaration
Swift
open func simulateTemporaryAuthTokenIssue() -
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/oldsyncscope.
Declaration
Swift
open func clearDeviceName() throws - Device registration is only available to applications that have been
granted the
-
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 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/oldsyncscope.
Declaration
Swift
open func ensureCapabilities(supportedCapabilities: [DeviceCapability]) throws -> LocalDevice -
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.It will only return active sessions. For example, if a user has disconnected the service from their account, it wouldn’t appear in this list.
Declaration
Swift
open func getAttachedClients() throws -> [AttachedClient] -
Get the device id registered for this application.
# Notes
- If the application has not registered a device record, this method will
throw an
Othererror. - (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/oldsyncscope.
Declaration
Swift
open func getCurrentDeviceId() throws -> String - If the application has not registered a device record, this method will
throw an
-
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/oldsyncscope.
Declaration
Swift
open func getDevices(ignoreCache: Bool) throws -> [Device] -
Create a new device record for this application.
💾 This method alters the persisted account state.
This method register 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 applicationdevice_type- the type of device the application is installed onsupported_capabilities- the set of capabilities 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/oldsyncscope.
Declaration
Swift
open func initializeDevice(name: String, deviceType: DeviceType, supportedCapabilities: [DeviceCapability]) throws -> LocalDevice -
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/oldsyncscope.
Declaration
Swift
open func setDeviceName(displayName: String) throws -> LocalDevice -
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
profilescope. - 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
Authenticationerror.
Declaration
Swift
open func getProfile(ignoreCache: Bool) throws -> Profile -
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
CloseTabscapability, this method can be used to close its tabs.Declaration
Swift
open func closeTabs(targetDeviceId: String, urls: [String]) throws -> CloseTabsResult -
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
open func handlePushMessage(payload: String) throws -> AccountEvent -
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
CommandReceivedevent. 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/oldsyncscope.
Declaration
Swift
open func pollDeviceCommands() throws -> [IncomingDeviceCommand] - Device commands are typically delivered via push message and the
-
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
SendTabcapability, 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
Othererror. - (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/oldsyncscope.
Declaration
Swift
open func sendSingleTab(targetDeviceId: String, title: String, url: String, isPrivate: Bool = false) throws - If the given device id does not existing or is not capable of receiving tabs,
this method will throw an
-
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_messagemethod 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/oldsyncscope.
Declaration
Swift
open func setPushSubscription(subscription: DevicePushSubscription) throws -> LocalDevice -
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
open func toJson() throws -> String -
Collect and return telemetry about send-tab attempts.
Applications that register the
SendTabcapability 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
open func gatherTelemetry() throws -> String -
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
open func authorizeCodeUsingSessionToken(params: AuthorizationParameters) throws -> String -
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
open func clearAccessTokenCache() -
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_tokenin 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- space-separated list of OAuth scopes to be granted by the token.- Each scope must have been requested during the signin flow, or be a scope which the server might offer automatically in some account-specific cases.
- Scope order is not significant;
"a b"and"b a"are equivalent. - When a single scope is requested and it has an associated scoped key
(e.g.
https://identity.mozilla.com/apps/oldsync), the returnedAccessTokenInfo::keywill be populated; for multi-scope requests it isNone. use_cache- optionally set to false to force a new token request. The fetched token will still be cached for laterget_access_tokencalls.
# Notes
- If the application receives an authorization error when trying to use the resulting
token, it should call
clear_access_token_cachebefore requesting a fresh token.
Declaration
Swift
open func getAccessToken(scope: String, useCache: Bool = true) throws -> AccessTokenInfo -
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/sessionscope.
Declaration
Swift
open func getSessionToken() throws -> String -
Builds a complete
signedInUserJSON object for a WebChannelfxaccounts:fxa_statusresponse, embedding the session token without exposing it to the browser layer. Email and uid are read from the cached profile in internal state. ReturnsNoneif no session token is available.Declaration
Swift
open func getSignedInUserForWebChannel() -> String? -
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
open func handleSessionTokenChange(sessionToken: String) throws -
Handle a WebChannel password-change notification by exchanging the new session token for a new refresh token.
💾 This method alters the persisted account state.
Declaration
Swift
open func handleWebChannelPasswordChange(jsonPayload: String) throws -
Check whether the account has already been granted the given OAuth scope(s).
This checks whether the refresh token has every specified scope.
# Arguments
scope- space-separated list of OAuth scopes. Order is not significant.
Declaration
Swift
open func hasScope(scope: String) -> Bool