Backup Service Reference

class BackupService(backupResources=DefaultBackupResources)

The BackupService class orchestrates the scheduling and creation of profile backups. It also does most of the heavy lifting for the restoration of a profile backup.

Create a BackupService instance.

Arguments:
  • backupResources (object) – Object containing BackupResource classes to associate with this service.

BackupService.BackupService

Create a BackupService instance.

BackupService._state

type: object

An object holding the current state of the BackupService instance, for the purposes of representing it in the user interface. Ideally, this would be named #state instead of #_state, but sphinx-js seems to be fairly unhappy with that coupled with the state getter.

BackupService.backupFileName

The name of the backup archive file. Should be localized.

See also

BackupService.backupFolderName

The name of the backup folder. Should be localized.

See also

BackupService.backupSchedulerInitted

type: boolean

True if the backup scheduler system has been initted via initBackupScheduler().

BackupService.encState

type: ArchiveEncryptionState|null|undefined

The currently used ArchiveEncryptionState. Callers should use loadEncryptionState() instead, to ensure that any pre-serialized encryption state has been read in and deserialized.

This member can be in 3 states:

  1. undefined - no attempt has been made to load encryption state from disk yet.

  2. null - encryption is not enabled.

  3. ArchiveEncryptionState - encryption is enabled.

BackupService.idleThresholdSeconds

type: number

The value of IDLE_THRESHOLD_SECONDS_PREF_NAME at the time that initBackupScheduler was called. This is recorded so that if the preference changes at runtime, that we properly remove the idle observer in uninitBackupScheduler, since it’s mapped to the idle time value.

BackupService.instance

type: BackupService|null

The BackupService singleton instance.

BackupService.loadEncryptionStatePromise

type: Promise

The internal promise that is created on the first call to loadEncryptionState.

BackupService.manifestSchemaPromise

type: Promise.<object>

A promise that resolves to the schema for the backup manifest that this BackupService uses when creating a backup. This should be accessed via the MANIFEST_SCHEMA static getter.

BackupService.observer

type: function

An ES6 class that extends EventTarget cannot, apparently, be coerced into a nsIObserver, even when we define QueryInterface. We work around this limitation by having the observer be a function that we define at registration time. We hold a reference to the observer so that we can properly unregister.

BackupService.postRecoveryComplete

Returns a reference to a Promise that will resolve with undefined once postRecovery steps have had a chance to run. This will also be resolved with undefined if no postRecovery steps needed to be run.

BackupService.postRecoveryPromise

type: Promise.<undefined>

A Promise that will resolve once the postRecovery steps are done. It will also resolve if postRecovery steps didn’t need to run.

BackupService.postRecoveryResolver

type: function

The resolving function for #postRecoveryPromise, which should be called by checkForPostRecovery() before exiting.

BackupService.recoveryInProgress

type: boolean

True if a recovery is currently in progress.

BackupService.resources

type: Map.<string, BackupResource>

Map of instantiated BackupResource classes.

BackupService.state

type: object

Returns a state object describing the state of the BackupService for the purposes of representing it in the user interface. The returned state object is immutable.

BackupService.ARCHIVE_ENCRYPTION_STATE_FILE

type: string

The name of the serialized ArchiveEncryptionState that is written to disk if encryption is enabled.

BackupService.ARCHIVE_TEMPLATE

type: string

Returns the chrome:// URI string for the template that should be used to construct the single-file archive.

BackupService.BACKUP_DIR_NAME

The localized name for the user’s backup folder.

BackupService.BACKUP_FILE_NAME

The localized name for the user’s backup archive file. This will have .html appended to it before writing the archive file.

BackupService.COMPRESSION_LEVEL

type: number

The level of Zip compression to use on the zipped staging folder.

BackupService.DEFAULT_PARENT_DIR_PATH

The path of the default parent directory for saving backups. The current default is the Documents directory.

BackupService.MANIFEST_FILE_NAME

type: string

The name of the backup manifest file.

BackupService.MANIFEST_SCHEMA

type: Promise.<object>

The current schema version of the backup manifest that this BackupService uses when creating a backup.

BackupService.POST_RECOVERY_FILE_NAME

type: string

The name of the post recovery file written into the newly created profile directory just after a profile is recovered from a backup.

BackupService.PROFILE_FOLDER_NAME

type: string

The name of the folder within the profile folder where this service reads and writes state to.

BackupService.RECOVERY_OSKEYSTORE_LABEL

type: string

The native OSKeyStore label used for the temporary recovery store. The temporary recovery store is initialized with the original OSKeyStore secret that was included in an encrypted backup, and then used by any BackupResource’s that need to decrypt / re-encrypt OSKeyStore secrets for the current device.

BackupService.RECOVERY_ZIP_FILE_NAME

type: string

Returns the filename used for the intermediary compressed ZIP file that is extracted from archives during recovery.

BackupService.SCHEMAS

type: object

Returns the SCHEMAS constants, which is a key/value store of constants.

BackupService.SNAPSHOTS_FOLDER_NAME

type: string

The name of the folder within the PROFILE_FOLDER_NAME where the staging folder / prior backups will be stored.

BackupService.checkForPostRecovery(profilePath="PathUtils.profileDir")

Checks for the POST_RECOVERY_FILE_NAME in the current profile directory. If one exists, instantiates any relevant BackupResource’s, and calls postRecovery() on them with the appropriate entry from the file. Once this is done, deletes the file.

The file is deleted even if one of the postRecovery() steps rejects or fails.

This function resolves silently if the POST_RECOVERY_FILE_NAME file does not exist, which should be the majority of cases.

Arguments:
  • profilePath (string) – The profile path to look for the POST_RECOVERY_FILE_NAME file. Defaults to the current profile.

Returns:

Promise.<undefined>

BackupService.createArchive(archivePath, templateURI, compressedBackupSnapshotPath, encState, backupMetadata, options)

Creates a portable, potentially encrypted single-file archive containing a compressed backup snapshot. The single-file archive is a specially crafted HTML file that embeds the compressed backup snapshot and backup metadata.

Arguments:
  • archivePath (string) – The path to write the single-file archive to.

  • templateURI (string) – A URI pointing at a template for the HTML content for the page. This is what is visible if the file is loaded in a web browser.

  • compressedBackupSnapshotPath (string) – The path on the file system where the compressed backup snapshot exists.

  • encState (ArchiveEncryptionState|null) – The ArchiveEncryptionState to encrypt the backup with, if encryption is enabled. If null is passed, the backup will not be encrypted.

  • backupMetadata (object) – The metadata for the backup, which is also stored in the backup manifest of the compressed backup snapshot.

  • options (object) – Options to pass to the worker, mainly for testing.

  • options.chunkSize (object) – The chunk size to break the bytes into.

BackupService.createBackup(options)

Create a backup of the user’s profile.

Arguments:
  • options (object) – Options for the backup.

  • options.profilePath (string) – The path to the profile to backup. By default, this is the current profile.

Returns:

Promise.<(CreateBackupResult|null)> – A promise that resolves to information about the backup that was created, or null if the backup failed.

BackupService.createBackupOnIdleDispatch()

Calls BackupService.createBackup at the next moment when the event queue is not busy with higher priority events. This is intentionally broken out into its own method to make it easier to stub out in tests.

BackupService.createBinaryReadableStream(archiveFile, startByteOffset, contentType)

A helper for BackupService.#extractCompressedSnapshotFromArchive that constructs a BinaryReadableStream for a single-file archive on the file system. The BinaryReadableStream will be used to read out the binary attachment from the archive.

Arguments:
  • archiveFile (nsIFile) – The single-file archive to create the BinaryReadableStream for.

  • startByteOffset (number) – The start byte offset of the MIME message.

  • contentType (string) – The Content-Type of the MIME message.

Returns:

ReadableStream

BackupService.decompressRecoveryFile(recoveryFilePath, recoveryFolderDestPath)

Decompressed a compressed recovery file into recoveryFolderDestPath.

Arguments:
  • recoveryFilePath (string) – The path to the compressed recovery file to decompress.

  • recoveryFolderDestPath (string) – The path to the folder that the compressed recovery file should be decompressed within.

Returns:

Promise.<undefined>

BackupService.deleteLastBackup()

Will attempt to delete the last created single-file archive if it exists. Once done, this method will also check the parent folder to see if it’s empty. If so, then the folder is removed.

Returns:

Promise.<undefined>

BackupService.disableEncryption(profilePath="PathUtils.profileDir")

Disables encryption of backups. Throws is encryption is already disabled.

Arguments:
  • profilePath (string) – The profile path where the encryption state exists. This is only used for testing.

Throws:

Exception

Returns:

Promise.<undefined>

BackupService.editBackupLocation(window)

Shows a native folder picker to set the location to write the single-file archive files.

Arguments:
  • window (ChromeWindow) – The top-level browsing window to associate the file picker with.

Returns:

Promise.<undefined>

BackupService.enableEncryption(password, profilePath="PathUtils.profileDir")

Enables encryption for backups, allowing sensitive data to be backed up. Throws if encryption is already enabled. After enabling encryption, that state is written to disk.

Arguments:
  • password (string) – A non-blank password (“recovery code”) that can be used to derive keys for encrypting the backup.

  • profilePath (string) – The profile path where the encryption state will be written. This is only used for testing.

Throws:

Exception

BackupService.extractCompressedSnapshotFromArchive(archivePath, extractionDestPath, recoveryCode="null")

Attempts to extract the compressed backup snapshot from a single-file archive, and write the extracted file to extractionDestPath. This may reject if the single-file archive appears malformed or cannot be properly decrypted. If the backup was encrypted, a native nsIOSKeyStore is also initialized with label BackupService.RECOVERY_OSKEYSTORE_LABEL with the secret used on the original backup machine. Callers are responsible for clearing this secret after any decryptions with it are completed.

NOTE: Currently, this base64 decoding currently occurs on the main thread. We may end up moving all of this into the Archive Worker if we can modify IOUtils to allow writing via a stream.

Arguments:
  • archivePath (string) – The single-file archive that contains the backup.

  • extractionDestPath (string) – The path to write the extracted file to.

  • recoveryCode (string) – The recovery code to decrypt an encrypted backup with.

Returns:

Promise.<undefined, Error>

BackupService.finalizeSingleFileArchive(sourcePath, destFolder, metadata)

Moves the single-file archive into its configured location with a filename that is sanitized and contains a timecode. This also removes any existing single-file archives in that same folder after the move completes.

Arguments:
  • sourcePath (string) – The file system location of the single-file archive prior to the move.

  • destFolder (string) – The folder that the single-file archive is configured to be eventually written to.

  • metadata (object) – The metadata for the backup. See the BackupManifest schema for details.

Returns:

Promise.<string> – Resolves with the path that the single-file archive was moved to.

BackupService.generateArchiveDateSuffix(date)

Generates a string from a Date in the form of:

YYYYMMDD-HHMM

Arguments:
  • date (Date) – The date to convert into the archive date suffix.

Returns:

string

BackupService.getBackupFileInfo(backupFilePath)

Gets a sample from a given backup file and sets a subset of that as the backupFileInfo in the backup service state.

Called when getting a info for an archive to potentially restore.

Arguments:
  • backupFilePath (string) – path to the backup file to sample.

BackupService.getIconFromFilePath(path)

Returns the moz-icon URL of a file. To get the moz-icon URL, the file path is convered to a fileURI. If there is a problem retreiving the moz-icon due to an invalid file path, return null instead.

Arguments:
  • path (string) – Path of the file to read its icon from.

Returns:

string|null – The moz-icon URL of the specified file, or null if the icon cannot be retreived.

BackupService.initBackupScheduler()

Initializes the backup scheduling system. This should be done shortly after startup. It is exposed as a public method mainly for ease in testing.

The scheduler will automatically uninitialize itself on the quit-application-granted observer notification.

Returns:

Promise.<undefined>

BackupService.loadEncryptionState(profilePath="PathUtils.profileDir")

Returns the current ArchiveEncryptionState. This method will only attempt to read the state from the disk the first time it is called.

Arguments:
  • profilePath (string) – The profile path where the encryption state might exist. This is only used for testing.

Returns:

Promise.<ArchiveEncryptionState>

BackupService.onIdle()

Called when the nsIUserIdleService reports that user input events have not been sent to the application for at least IDLE_THRESHOLD_SECONDS_PREF_NAME seconds.

BackupService.onObserve(_subject, topic)

Called by this.#observer on idle from the nsIUserIdleService or quit-application-granted from the nsIObserverService. Exposed as a public method mainly for ease in testing.

Arguments:
  • _subject (nsISupports|null) – The nsIUserIdleService for the idle notification, and null for the quit-application-granted topic.

  • topic (string) – The topic that the notification belongs to.

BackupService.onUpdateLocationDirPath(newDirPath)

Updates backupDirPath in the backup service state. Should be called every time the value for browser.backup.location changes.

Arguments:
  • newDirPath (string) – the new directory path for storing backups

BackupService.onUpdateScheduledBackups(isScheduledBackupsEnabled)

Updates scheduledBackupsEnabled in the backup service state. Should be called every time the value for browser.backup.scheduled.enabled changes.

Arguments:
  • isScheduledBackupsEnabled (boolean) – True if scheduled backups are enabled. Else false.

BackupService.recoverFromBackupArchive(archivePath, recoveryCode="null", shouldLaunch=false, profilePath=PathUtils.profileDir, profileRootPath="null")

Given a backup archive at archivePath, this method does the following:

  1. Potentially decrypts, and then extracts the compressed backup snapshot from the archive to a file named BackupService.RECOVERY_ZIP_FILE_NAME in the PROFILE_FOLDER_NAME folder.

  2. Decompresses that file into a subdirectory of PROFILE_FOLDER_NAME named “recovery”.

  3. Deletes the BackupService.RECOVERY_ZIP_FILE_NAME file.

  4. Calls into recoverFromSnapshotFolder on the decompressed “recovery” folder.

  5. Optionally launches the newly created profile.

  6. Returns the name of the newly created profile directory.

Arguments:
  • archivePath (string) – The path to the single-file backup archive on the file system.

  • recoveryCode (string|null) – The recovery code to use to attempt to decrypt the archive if it was encrypted.

  • shouldLaunch (boolean) – An optional argument that specifies whether an instance of the app should be launched with the newly recovered profile after recovery is complete.

  • profilePath (boolean) – The profile path where the recovery files will be written to within the PROFILE_FOLDER_NAME. This is only used for testing.

  • profileRootPath (string) – An optional argument that specifies the root directory where the new profile directory should be created. If not provided, the default profile root directory will be used. This is primarily meant for testing.

Throws:

Exception – In the event that unpacking the archive, decompressing the snapshot, or recovery from the snapshot somehow failed.

Returns:

Promise.<nsIToolkitProfile> – The nsIToolkitProfile that was created for the recovered profile.

BackupService.recoverFromSnapshotFolder(recoveryPath, shouldLaunch=false, profileRootPath="null", encState=null)

Given a decompressed backup archive at recoveryPath, this method does the following:

  1. Reads in the backup manifest from the archive and ensures that it is valid.

  2. Creates a new named profile directory using the same name as the one found in the backup manifest, but with a different prefix.

  3. Iterates over each resource in the manifest and calls the recover() method on each found BackupResource, passing in the associated ManifestEntry from the backup manifest, and collects any post-recovery data from those resources.

  4. Writes a post-recovery.json file into the newly created profile directory.

  5. Returns the name of the newly created profile directory.

  6. Regardless of whether or not recovery succeeded, clears the native OSKeyStore of any secret labeled with BackupService.RECOVERY_OSKEYSTORE_LABEL.

Arguments:
  • recoveryPath (string) – The path to the decompressed backup archive on the file system.

  • shouldLaunch (boolean) – An optional argument that specifies whether an instance of the app should be launched with the newly recovered profile after recovery is complete.

  • profileRootPath (string) – An optional argument that specifies the root directory where the new profile directory should be created. If not provided, the default profile root directory will be used. This is primarily meant for testing.

  • encState (ArchiveEncryptionState) – Set if the backup being recovered was encrypted. This implies that the profile being recovered was configured to create encrypted backups. This ArchiveEncryptionState is therefore needed to generate the ARCHIVE_ENCRYPTION_STATE_FILE for the recovered profile (since the original ARCHIVE_ENCRYPTION_STATE_FILE was intentionally not backed up, as the recovery device might have a different OSKeyStore secret).

Throws:

Exception – In the event that recovery somehow failed.

Returns:

Promise.<nsIToolkitProfile> – The nsIToolkitProfile that was created for the recovered profile.

BackupService.renderTemplate(templateURI, isEncrypted, backupMetadata)

Given a URI to an HTML template for the single-file backup archive, produces the static markup that will then be used as the beginning of that single-file backup archive.

Arguments:
  • templateURI (string) – A URI pointing at a template for the HTML content for the page. This is what is visible if the file is loaded in a web browser.

  • isEncrypted (boolean) – True if the template should indicate that the backup is encrypted.

  • backupMetadata (object) – The metadata for the backup, which is also stored in the backup manifest of the compressed backup snapshot.

Returns:

Promise.<string>

BackupService.resolveArchiveDestFolderPath(configuredDestFolderPath)

Attempts to find the right folder to write the single-file archive to, and if it does not exist, to create it.

If the configured destination’s parent folder does not exist and cannot be recreated, we will fall back to the defaultParentDirPath. If defaultParentDirPath happens to not exist or cannot be created, we will fall back to the home directory. If _that_ folder does not exist and cannot be recreated, this method will reject.

Arguments:
  • configuredDestFolderPath (string) – The currently configured destination folder for the archive.

Returns:

Promise.<string, Error>

Computes the appropriate link to place in the single-file archive for downloading a version of this application for the same update channel.

When bug 1905909 lands, we’ll first check to see if there are download links available in Remote Settings.

If there aren’t any, we will fallback by looking for preference values at browser.backup.template.fallback-download.${updateChannel}.

If no such preference exists, a final “ultimate” fallback download link is chosen for the release channel.

Arguments:
  • updateChannel (string) – The current update channel for the application, as provided by AppConstants.MOZ_UPDATE_CHANNEL.

Returns:

Promise.<string>

BackupService.sampleArchive(archivePath)

Reads from a file to determine if it seems to be a backup archive, and if so, resolves with some information about the archive without actually unpacking it. The returned Promise may reject if the file does not appear to be a backup archive, or the backup archive appears to have been corrupted somehow.

Arguments:
  • archivePath (string) – The path to the archive file to sample.

Returns:

Promise.<SampleArchiveResult, Error>

BackupService.setParentDirPath(parentDirPath)

Sets the parent directory of the backups folder. Calling this function will update browser.backup.location.

Arguments:
  • parentDirPath (string) – directory path

BackupService.setScheduledBackups(shouldEnableScheduledBackups)

Sets browser.backup.scheduled.enabled to true or false.

Arguments:
  • shouldEnableScheduledBackups (boolean) – true if scheduled backups should be enabled. Else, false.

BackupService.stateUpdate()

Dispatches an event to let listeners know that the BackupService state object has been updated.

BackupService.takeMeasurements()

Take measurements of the current profile state for Telemetry.

Returns:

Promise.<undefined>

BackupService.uninitBackupScheduler()

Uninitializes the backup scheduling system.

Returns:

Promise.<undefined>

static BackupService.get()

Returns a reference to the BackupService singleton. If the singleton has not been initialized, an error is thrown.

Returns:

BackupService

static BackupService.getSchemaForVersion(schemaType, version)

Returns the schema for the schemaType for a given version.

Arguments:
  • schemaType (number) – One of the constants from SCHEMAS.

  • version (number) – The version of the schema to return.

Returns:

Promise.<object>

static BackupService.init()

Returns a reference to a BackupService singleton. If this is the first time that this getter is accessed, this causes the BackupService singleton to be be instantiated.