Backed out 13 changesets (bug 1296767) for xpcshell failures a=backout CLOSED TREE

Backed out changeset 41ed77788333 (bug 1296767)
Backed out changeset 1c0c9289b532 (bug 1296767)
Backed out changeset 50294db1d871 (bug 1296767)
Backed out changeset 26c065f79c54 (bug 1296767)
Backed out changeset 0362a78d6978 (bug 1296767)
Backed out changeset 4e71cf94e4ee (bug 1296767)
Backed out changeset f6f59447d22a (bug 1296767)
Backed out changeset 6c9b792cc296 (bug 1296767)
Backed out changeset 46a52b10a868 (bug 1296767)
Backed out changeset 5d70d87d2a8f (bug 1296767)
Backed out changeset 8219686be6a2 (bug 1296767)
Backed out changeset 0a989b0cea67 (bug 1296767)
Backed out changeset 9f59a0b75c1f (bug 1296767)

MozReview-Commit-ID: 2XBNsd8JrZL

--HG--
extra : amend_source : 1afafaa8127fcebac31ce1d7743dc16872fa0522
This commit is contained in:
Wes Kocher 2017-01-26 11:16:12 -08:00
parent 6fdacf6368
commit c3cc3b6407
150 changed files with 10045 additions and 541 deletions

View File

@ -268,6 +268,7 @@
@RESPATH@/components/satchel.xpt
@RESPATH@/components/saxparser.xpt
@RESPATH@/components/sessionstore.xpt
@RESPATH@/components/services-crypto-component.xpt
@RESPATH@/components/captivedetect.xpt
@RESPATH@/components/shellservice.xpt
@RESPATH@/components/shistory.xpt

View File

@ -16,6 +16,7 @@ Cu.import("resource://gre/modules/FxAccountsCommon.js", fxAccountsCommon);
Cu.import("resource://services-sync/util.js");
const PREF_LAST_FXA_USER = "identity.fxaccounts.lastSignedInUserHash";
const PREF_SYNC_SHOW_CUSTOMIZATION = "services.sync-setup.ui.showCustomizationDialog";
const ACTION_URL_PARAM = "action";
@ -196,8 +197,9 @@ var wrapper = {
onLogin(accountData) {
log("Received: 'login'. Data:" + JSON.stringify(accountData));
// We don't act on customizeSync anymore, it used to open a dialog inside
// the browser to selecte the engines to sync but we do it on the web now.
if (accountData.customizeSync) {
Services.prefs.setBoolPref(PREF_SYNC_SHOW_CUSTOMIZATION, true);
}
delete accountData.customizeSync;
// sessionTokenContext is erroneously sent by the content server.
// https://github.com/mozilla/fxa-content-server/issues/2766
@ -304,6 +306,18 @@ var wrapper = {
// Button onclick handlers
function handleOldSync() {
let chromeWin = window
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow)
.QueryInterface(Ci.nsIDOMChromeWindow);
let url = Services.urlFormatter.formatURLPref("app.support.baseURL") + "old-sync";
chromeWin.switchToTabHavingURI(url, true);
}
function getStarted() {
show("remote");
@ -491,7 +505,10 @@ document.addEventListener("DOMContentLoaded", function() {
var buttonRetry = document.getElementById("buttonRetry");
buttonRetry.addEventListener("click", retry);
var buttonOpenPrefs = document.getElementById("buttonOpenPrefs");
var oldsync = document.getElementById("oldsync");
oldsync.addEventListener("click", handleOldSync);
var buttonOpenPrefs = document.getElementById("buttonOpenPrefs")
buttonOpenPrefs.addEventListener("click", openPrefs);
}, {capture: true, once: true});

View File

@ -63,6 +63,10 @@
<div class="button-row">
<button id="buttonGetStarted" class="button" tabindex="1">&aboutAccountsConfig.startButton.label;</button>
</div>
<div class="links">
<button id="oldsync" tabindex="2">&aboutAccountsConfig.useOldSync.label;</button>
</div>
</section>
</div>

View File

@ -4,6 +4,8 @@
var gFxAccounts = {
SYNC_MIGRATION_NOTIFICATION_TITLE: "fxa-migration",
_initialized: false,
_inCustomizationMode: false,
@ -23,6 +25,7 @@ var gFxAccounts = {
"weave:service:setup-complete",
"weave:service:sync:error",
"weave:ui:login:error",
"fxa-migration:state-changed",
this.FxAccountsCommon.ONLOGIN_NOTIFICATION,
this.FxAccountsCommon.ONLOGOUT_NOTIFICATION,
this.FxAccountsCommon.ON_PROFILE_CHANGE_NOTIFICATION,
@ -140,6 +143,9 @@ var gFxAccounts = {
observe(subject, topic, data) {
switch (topic) {
case "fxa-migration:state-changed":
this.onMigrationStateChanged(data, subject);
break;
case this.FxAccountsCommon.ONPROFILE_IMAGE_CHANGE_NOTIFICATION:
this.updateUI();
break;
@ -149,18 +155,78 @@ var gFxAccounts = {
}
},
handleEvent(event) {
this._inCustomizationMode = event.type == "customizationstarting";
this.updateUI();
onMigrationStateChanged() {
// Since we nuked most of the migration code, this notification will fire
// once after legacy Sync has been disconnected (and should never fire
// again)
let nb = window.document.getElementById("global-notificationbox");
let msg = this.strings.GetStringFromName("autoDisconnectDescription")
let signInLabel = this.strings.GetStringFromName("autoDisconnectSignIn.label");
let signInAccessKey = this.strings.GetStringFromName("autoDisconnectSignIn.accessKey");
let learnMoreLink = this.fxaMigrator.learnMoreLink;
let buttons = [
{
label: signInLabel,
accessKey: signInAccessKey,
callback: () => {
this.openPreferences();
}
}
];
let fragment = document.createDocumentFragment();
let msgNode = document.createTextNode(msg);
fragment.appendChild(msgNode);
if (learnMoreLink) {
let link = document.createElement("label");
link.className = "text-link";
link.setAttribute("value", learnMoreLink.text);
link.href = learnMoreLink.href;
fragment.appendChild(link);
}
nb.appendNotification(fragment,
this.SYNC_MIGRATION_NOTIFICATION_TITLE,
undefined,
nb.PRIORITY_WARNING_LOW,
buttons);
// ensure the hamburger menu reflects the newly disconnected state.
this.updateAppMenuItem();
},
handleEvent(event) {
this._inCustomizationMode = event.type == "customizationstarting";
this.updateAppMenuItem();
},
// Note that updateUI() returns a Promise that's only used by tests.
updateUI() {
// It's possible someone signed in to FxA after seeing our notification
// about "Legacy Sync migration" (which now is actually "Legacy Sync
// auto-disconnect") so kill that notification if it still exists.
let nb = window.document.getElementById("global-notificationbox");
let n = nb.getNotificationWithValue(this.SYNC_MIGRATION_NOTIFICATION_TITLE);
if (n) {
nb.removeNotification(n, true);
}
this.updateAppMenuItem();
},
// Note that updateAppMenuItem() returns a Promise that's only used by tests.
updateAppMenuItem() {
let profileInfoEnabled = false;
try {
profileInfoEnabled = Services.prefs.getBoolPref("identity.fxaccounts.profile_image.enabled");
} catch (e) { }
// Bail out if FxA is disabled.
if (!this.weave.fxAccountsEnabled) {
return Promise.resolve();
}
this.panelUIFooter.hidden = false;
// Make sure the button is disabled in customization mode.
@ -411,5 +477,8 @@ XPCOMUtils.defineLazyGetter(gFxAccounts, "FxAccountsCommon", function() {
return Cu.import("resource://gre/modules/FxAccountsCommon.js", {});
});
XPCOMUtils.defineLazyModuleGetter(gFxAccounts, "fxaMigrator",
"resource://services-sync/FxaMigrator.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "EnsureFxAccountsWebChannel",
"resource://gre/modules/FxAccountsWebChannel.jsm");

View File

@ -496,7 +496,7 @@
label="&syncSignIn.label;"
accesskey="&syncSignIn.accesskey;"
observes="sync-setup-state"
oncommand="gSyncUI.openPrefs('menubar')"/>
oncommand="gSyncUI.openSetup(null, 'menubar')"/>
<menuitem id="sync-syncnowitem"
label="&syncSyncNowItem.label;"
accesskey="&syncSyncNowItem.accesskey;"

View File

@ -97,22 +97,41 @@ var gSyncUI = {
// Returns a promise that resolves with true if Sync needs to be configured,
// false otherwise.
_needsSetup() {
return fxAccounts.getSignedInUser().then(user => {
// We want to treat "account needs verification" as "needs setup".
return !(user && user.verified);
});
// If Sync is configured for FxAccounts then we do that promise-dance.
if (this.weaveService.fxAccountsEnabled) {
return fxAccounts.getSignedInUser().then(user => {
// We want to treat "account needs verification" as "needs setup".
return !(user && user.verified);
});
}
// We are using legacy sync - check that.
let firstSync = "";
try {
firstSync = Services.prefs.getCharPref("services.sync.firstSync");
} catch (e) { }
return Promise.resolve(Weave.Status.checkSetup() == Weave.CLIENT_NOT_CONFIGURED ||
firstSync == "notReady");
},
// Returns a promise that resolves with true if the user currently signed in
// to Sync needs to be verified, false otherwise.
_needsVerification() {
return fxAccounts.getSignedInUser().then(user => {
// If there is no user, they can't be in a "needs verification" state.
if (!user) {
return false;
}
return !user.verified;
});
// For callers who care about the distinction between "needs setup" and
// "needs verification"
if (this.weaveService.fxAccountsEnabled) {
return fxAccounts.getSignedInUser().then(user => {
// If there is no user, they can't be in a "needs verification" state.
if (!user) {
return false;
}
return !user.verified;
});
}
// Otherwise we are configured for legacy Sync, which has no verification
// concept.
return Promise.resolve(false);
},
// Note that we don't show login errors in a notification bar here, but do
@ -248,7 +267,7 @@ var gSyncUI = {
handleToolbarButton() {
this._needsSetup().then(needsSetup => {
if (needsSetup || this.loginFailed()) {
this.openPrefs();
this.openSetup();
} else {
this.doSync();
}
@ -258,12 +277,46 @@ var gSyncUI = {
},
/**
* Open the Sync preferences.
* Invoke the Sync setup wizard.
*
* @param wizardType
* Indicates type of wizard to launch:
* null -- regular set up wizard
* "pair" -- pair a device first
* "reset" -- reset sync
* @param entryPoint
* Indicates the entrypoint from where this method was called.
*/
openPrefs(entryPoint = "syncbutton") {
openSetup: function SUI_openSetup(wizardType, entryPoint = "syncbutton") {
if (this.weaveService.fxAccountsEnabled) {
this.openPrefs(entryPoint);
} else {
let win = Services.wm.getMostRecentWindow("Weave:AccountSetup");
if (win)
win.focus();
else {
window.openDialog("chrome://browser/content/sync/setup.xul",
"weaveSetup", "centerscreen,chrome,resizable=no",
wizardType);
}
}
},
// Open the legacy-sync device pairing UI. Note used for FxA Sync.
openAddDevice() {
if (!Weave.Utils.ensureMPUnlocked())
return;
let win = Services.wm.getMostRecentWindow("Sync:AddDevice");
if (win)
win.focus();
else
window.openDialog("chrome://browser/content/sync/addDevice.xul",
"syncAddDevice", "centerscreen,chrome,resizable=no");
},
openPrefs(entryPoint) {
openPreferences("paneSync", { urlParams: { entrypoint: entryPoint } });
},
@ -321,10 +374,9 @@ var gSyncUI = {
return;
let email;
let user = yield fxAccounts.getSignedInUser();
if (user) {
email = user.email;
}
try {
email = Services.prefs.getCharPref("services.sync.username");
} catch (ex) {}
let needsSetup = yield this._needsSetup();
let needsVerification = yield this._needsVerification();

View File

@ -0,0 +1,157 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var Ci = Components.interfaces;
var Cc = Components.classes;
var Cu = Components.utils;
Cu.import("resource://services-sync/main.js");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
const PIN_PART_LENGTH = 4;
const ADD_DEVICE_PAGE = 0;
const SYNC_KEY_PAGE = 1;
const DEVICE_CONNECTED_PAGE = 2;
var gSyncAddDevice = {
init: function init() {
this.pin1.setAttribute("maxlength", PIN_PART_LENGTH);
this.pin2.setAttribute("maxlength", PIN_PART_LENGTH);
this.pin3.setAttribute("maxlength", PIN_PART_LENGTH);
this.nextFocusEl = {pin1: this.pin2,
pin2: this.pin3,
pin3: this.wizard.getButton("next")};
this.throbber = document.getElementById("pairDeviceThrobber");
this.errorRow = document.getElementById("errorRow");
// Kick off a sync. That way the server will have the most recent data from
// this computer and it will show up immediately on the new device.
Weave.Service.scheduler.scheduleNextSync(0);
},
onPageShow: function onPageShow() {
this.wizard.getButton("back").hidden = true;
switch (this.wizard.pageIndex) {
case ADD_DEVICE_PAGE:
this.onTextBoxInput();
this.wizard.canRewind = false;
this.wizard.getButton("next").hidden = false;
this.pin1.focus();
break;
case SYNC_KEY_PAGE:
this.wizard.canAdvance = false;
this.wizard.canRewind = true;
this.wizard.getButton("back").hidden = false;
this.wizard.getButton("next").hidden = true;
document.getElementById("weavePassphrase").value =
Weave.Utils.hyphenatePassphrase(Weave.Service.identity.syncKey);
break;
case DEVICE_CONNECTED_PAGE:
this.wizard.canAdvance = true;
this.wizard.canRewind = false;
this.wizard.getButton("cancel").hidden = true;
break;
}
},
onWizardAdvance: function onWizardAdvance() {
switch (this.wizard.pageIndex) {
case ADD_DEVICE_PAGE:
this.startTransfer();
return false;
case DEVICE_CONNECTED_PAGE:
window.close();
return false;
}
return true;
},
startTransfer: function startTransfer() {
this.errorRow.hidden = true;
// When onAbort is called, Weave may already be gone.
const JPAKE_ERROR_USERABORT = Weave.JPAKE_ERROR_USERABORT;
let self = this;
let jpakeclient = this._jpakeclient = new Weave.JPAKEClient({
onPaired: function onPaired() {
let credentials = {account: Weave.Service.identity.account,
password: Weave.Service.identity.basicPassword,
synckey: Weave.Service.identity.syncKey,
serverURL: Weave.Service.serverURL};
jpakeclient.sendAndComplete(credentials);
},
onComplete: function onComplete() {
delete self._jpakeclient;
self.wizard.pageIndex = DEVICE_CONNECTED_PAGE;
// Schedule a Sync for soonish to fetch the data uploaded by the
// device with which we just paired.
Weave.Service.scheduler.scheduleNextSync(Weave.Service.scheduler.activeInterval);
},
onAbort: function onAbort(error) {
delete self._jpakeclient;
// Aborted by user, ignore.
if (error == JPAKE_ERROR_USERABORT) {
return;
}
self.errorRow.hidden = false;
self.throbber.hidden = true;
self.pin1.value = self.pin2.value = self.pin3.value = "";
self.pin1.disabled = self.pin2.disabled = self.pin3.disabled = false;
self.pin1.focus();
}
});
this.throbber.hidden = false;
this.pin1.disabled = this.pin2.disabled = this.pin3.disabled = true;
this.wizard.canAdvance = false;
let pin = this.pin1.value + this.pin2.value + this.pin3.value;
let expectDelay = false;
jpakeclient.pairWithPIN(pin, expectDelay);
},
onWizardBack: function onWizardBack() {
if (this.wizard.pageIndex != SYNC_KEY_PAGE)
return true;
this.wizard.pageIndex = ADD_DEVICE_PAGE;
return false;
},
onWizardCancel: function onWizardCancel() {
if (this._jpakeclient) {
this._jpakeclient.abort();
delete this._jpakeclient;
}
return true;
},
onTextBoxInput: function onTextBoxInput(textbox) {
if (textbox && textbox.value.length == PIN_PART_LENGTH)
this.nextFocusEl[textbox.id].focus();
this.wizard.canAdvance = (this.pin1.value.length == PIN_PART_LENGTH
&& this.pin2.value.length == PIN_PART_LENGTH
&& this.pin3.value.length == PIN_PART_LENGTH);
},
goToSyncKeyPage: function goToSyncKeyPage() {
this.wizard.pageIndex = SYNC_KEY_PAGE;
}
};
// onWizardAdvance() and onPageShow() are run before init() so we'll set
// these up as lazy getters.
["wizard", "pin1", "pin2", "pin3"].forEach(function(id) {
XPCOMUtils.defineLazyGetter(gSyncAddDevice, id, function() {
return document.getElementById(id);
});
});

View File

@ -0,0 +1,129 @@
<?xml version="1.0"?>
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<?xml-stylesheet href="chrome://browser/skin/syncSetup.css" type="text/css"?>
<?xml-stylesheet href="chrome://browser/skin/syncCommon.css" type="text/css"?>
<!DOCTYPE window [
<!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
<!ENTITY % syncBrandDTD SYSTEM "chrome://browser/locale/syncBrand.dtd">
<!ENTITY % syncSetupDTD SYSTEM "chrome://browser/locale/syncSetup.dtd">
%brandDTD;
%syncBrandDTD;
%syncSetupDTD;
]>
<wizard xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:html="http://www.w3.org/1999/xhtml"
id="wizard"
title="&pairDevice.title.label;"
windowtype="Sync:AddDevice"
persist="screenX screenY"
onwizardnext="return gSyncAddDevice.onWizardAdvance();"
onwizardback="return gSyncAddDevice.onWizardBack();"
onwizardcancel="gSyncAddDevice.onWizardCancel();"
onload="gSyncAddDevice.init();">
<script type="application/javascript"
src="chrome://browser/content/sync/addDevice.js"/>
<script type="application/javascript"
src="chrome://browser/content/sync/utils.js"/>
<script type="application/javascript"
src="chrome://browser/content/utilityOverlay.js"/>
<script type="application/javascript"
src="chrome://global/content/printUtils.js"/>
<wizardpage id="addDevicePage"
label="&pairDevice.title.label;"
onpageshow="gSyncAddDevice.onPageShow();">
<description>
&pairDevice.dialog.description.label;
<label class="text-link"
value="&addDevice.showMeHow.label;"
href="https://services.mozilla.com/sync/help/add-device"/>
</description>
<separator class="groove-thin"/>
<description>
&addDevice.dialog.enterCode.label;
</description>
<separator class="groove-thin"/>
<vbox align="center">
<textbox id="pin1"
class="pin"
oninput="gSyncAddDevice.onTextBoxInput(this);"
onfocus="this.select();"
/>
<textbox id="pin2"
class="pin"
oninput="gSyncAddDevice.onTextBoxInput(this);"
onfocus="this.select();"
/>
<textbox id="pin3"
class="pin"
oninput="gSyncAddDevice.onTextBoxInput(this);"
onfocus="this.select();"
/>
</vbox>
<separator class="groove-thin"/>
<vbox id="pairDeviceThrobber" align="center" hidden="true">
<image/>
</vbox>
<hbox id="errorRow" pack="center" hidden="true">
<image class="statusIcon" status="error"/>
<label class="status"
value="&addDevice.dialog.tryAgain.label;"/>
</hbox>
<spacer flex="3"/>
<label class="text-link"
value="&addDevice.dontHaveDevice.label;"
onclick="gSyncAddDevice.goToSyncKeyPage();"/>
</wizardpage>
<!-- Need a non-empty label here, otherwise we get a default label on Mac -->
<wizardpage id="syncKeyPage"
label=" "
onpageshow="gSyncAddDevice.onPageShow();">
<description>
&addDevice.dialog.recoveryKey.label;
</description>
<spacer/>
<groupbox>
<label value="&recoveryKeyEntry.label;"
accesskey="&recoveryKeyEntry.accesskey;"
control="weavePassphrase"/>
<textbox id="weavePassphrase"
readonly="true"/>
</groupbox>
<groupbox align="center">
<description>&recoveryKeyBackup.description;</description>
<hbox>
<button id="printSyncKeyButton"
label="&button.syncKeyBackup.print.label;"
accesskey="&button.syncKeyBackup.print.accesskey;"
oncommand="gSyncUtils.passphrasePrint('weavePassphrase');"/>
<button id="saveSyncKeyButton"
label="&button.syncKeyBackup.save.label;"
accesskey="&button.syncKeyBackup.save.accesskey;"
oncommand="gSyncUtils.passphraseSave('weavePassphrase');"/>
</hbox>
</groupbox>
</wizardpage>
<wizardpage id="deviceConnectedPage"
label="&addDevice.dialog.connected.label;"
onpageshow="gSyncAddDevice.onPageShow();">
<vbox align="center">
<image id="successPageIcon"/>
</vbox>
<separator/>
<description class="normal">
&addDevice.dialog.successful.label;
</description>
</wizardpage>
</wizard>

View File

@ -0,0 +1,28 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
:root {
font-size: 80%;
}
#sync-customize-pane {
padding-inline-start: 74px;
background: top left url(chrome://browser/skin/sync-128.png) no-repeat;
background-size: 64px;
}
#sync-customize-title {
margin-inline-start: 0;
padding-bottom: 0.5em;
font-weight: bold;
}
#sync-customize-subtitle {
font-size: 90%;
}
checkbox {
margin: 0;
padding: 0.5em 0 0;
}

View File

@ -0,0 +1,25 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
Components.utils.import("resource://gre/modules/Services.jsm");
addEventListener("dialogaccept", function() {
let pane = document.getElementById("sync-customize-pane");
// First determine what the preference for the "global" sync enabled pref
// should be based on the engines selected.
let prefElts = pane.querySelectorAll("preferences > preference");
let syncEnabled = false;
for (let elt of prefElts) {
if (elt.name.startsWith("services.sync.") && elt.value) {
syncEnabled = true;
break;
}
}
Services.prefs.setBoolPref("services.sync.enabled", syncEnabled);
// and write the individual prefs.
pane.writePreferences(true);
window.arguments[0].accepted = true;
});

View File

@ -0,0 +1,67 @@
<?xml version="1.0"?>
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<?xml-stylesheet href="chrome://browser/content/sync/customize.css" type="text/css"?>
<!DOCTYPE dialog [
<!ENTITY % syncCustomizeDTD SYSTEM "chrome://browser/locale/syncCustomize.dtd">
%syncCustomizeDTD;
]>
<dialog id="sync-customize"
windowtype="Sync:Customize"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:html="http://www.w3.org/1999/xhtml"
title="&syncCustomize.dialog.title;"
buttonlabelaccept="&syncCustomize.acceptButton.label;"
buttons="accept">
<prefpane id="sync-customize-pane">
<preferences>
<preference id="engine.bookmarks" name="services.sync.engine.bookmarks" type="bool"/>
<preference id="engine.history" name="services.sync.engine.history" type="bool"/>
<preference id="engine.tabs" name="services.sync.engine.tabs" type="bool"/>
<preference id="engine.passwords" name="services.sync.engine.passwords" type="bool"/>
<preference id="engine.addons" name="services.sync.engine.addons" type="bool"/>
<preference id="engine.prefs" name="services.sync.engine.prefs" type="bool"/>
</preferences>
<label id="sync-customize-title" value="&syncCustomize.title;"/>
<description id="sync-customize-subtitle"
#ifdef XP_UNIX
value="&syncCustomizeUnix.description;"
#else
value="&syncCustomize.description;"
#endif
/>
<vbox align="start">
<checkbox label="&engine.tabs.label2;"
accesskey="&engine.tabs.accesskey;"
preference="engine.tabs"/>
<checkbox label="&engine.bookmarks.label;"
accesskey="&engine.bookmarks.accesskey;"
preference="engine.bookmarks"/>
<checkbox label="&engine.passwords.label;"
accesskey="&engine.passwords.accesskey;"
preference="engine.passwords"/>
<checkbox label="&engine.history.label;"
accesskey="&engine.history.accesskey;"
preference="engine.history"/>
<checkbox label="&engine.addons.label;"
accesskey="&engine.addons.accesskey;"
preference="engine.addons"/>
<checkbox label="&engine.prefs.label;"
accesskey="&engine.prefs.accesskey;"
preference="engine.prefs"/>
</vbox>
</prefpane>
<script type="application/javascript"
src="chrome://browser/content/sync/customize.js" />
</dialog>

View File

@ -0,0 +1,226 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var Ci = Components.interfaces;
var Cc = Components.classes;
Components.utils.import("resource://services-sync/main.js");
Components.utils.import("resource://gre/modules/Services.jsm");
var Change = {
_dialog: null,
_dialogType: null,
_status: null,
_statusIcon: null,
_firstBox: null,
_secondBox: null,
get _passphraseBox() {
delete this._passphraseBox;
return this._passphraseBox = document.getElementById("passphraseBox");
},
get _currentPasswordInvalid() {
return Weave.Status.login == Weave.LOGIN_FAILED_LOGIN_REJECTED;
},
get _updatingPassphrase() {
return this._dialogType == "UpdatePassphrase";
},
onLoad: function Change_onLoad() {
/* Load labels */
let introText = document.getElementById("introText");
let warningText = document.getElementById("warningText");
// load some other elements & info from the window
this._dialog = document.getElementById("change-dialog");
this._dialogType = window.arguments[0];
this._duringSetup = window.arguments[1];
this._status = document.getElementById("status");
this._statusIcon = document.getElementById("statusIcon");
this._statusRow = document.getElementById("statusRow");
this._firstBox = document.getElementById("textBox1");
this._secondBox = document.getElementById("textBox2");
this._dialog.getButton("finish").disabled = true;
this._dialog.getButton("back").hidden = true;
this._stringBundle =
Services.strings.createBundle("chrome://browser/locale/syncGenericChange.properties");
switch (this._dialogType) {
case "UpdatePassphrase":
case "ResetPassphrase":
document.getElementById("textBox1Row").hidden = true;
document.getElementById("textBox2Row").hidden = true;
document.getElementById("passphraseLabel").value
= this._str("new.recoverykey.label");
document.getElementById("passphraseSpacer").hidden = false;
if (this._updatingPassphrase) {
document.getElementById("passphraseHelpBox").hidden = false;
document.title = this._str("new.recoverykey.title");
introText.textContent = this._str("new.recoverykey.introText");
this._dialog.getButton("finish").label
= this._str("new.recoverykey.acceptButton");
} else {
document.getElementById("generatePassphraseButton").hidden = false;
document.getElementById("passphraseBackupButtons").hidden = false;
this._passphraseBox.setAttribute("readonly", "true");
let pp = Weave.Service.identity.syncKey;
if (Weave.Utils.isPassphrase(pp))
pp = Weave.Utils.hyphenatePassphrase(pp);
this._passphraseBox.value = pp;
this._passphraseBox.focus();
document.title = this._str("change.recoverykey.title");
introText.textContent = this._str("change.synckey.introText2");
warningText.textContent = this._str("change.recoverykey.warningText");
this._dialog.getButton("finish").label
= this._str("change.recoverykey.acceptButton");
if (this._duringSetup) {
this._dialog.getButton("finish").disabled = false;
}
}
break;
case "ChangePassword":
document.getElementById("passphraseRow").hidden = true;
let box1label = document.getElementById("textBox1Label");
let box2label = document.getElementById("textBox2Label");
box1label.value = this._str("new.password.label");
if (this._currentPasswordInvalid) {
document.title = this._str("new.password.title");
introText.textContent = this._str("new.password.introText");
this._dialog.getButton("finish").label
= this._str("new.password.acceptButton");
document.getElementById("textBox2Row").hidden = true;
} else {
document.title = this._str("change.password.title");
box2label.value = this._str("new.password.confirm");
introText.textContent = this._str("change.password3.introText");
warningText.textContent = this._str("change.password.warningText");
this._dialog.getButton("finish").label
= this._str("change.password.acceptButton");
}
break;
}
document.getElementById("change-page")
.setAttribute("label", document.title);
},
_clearStatus: function _clearStatus() {
this._status.value = "";
this._statusIcon.removeAttribute("status");
},
_updateStatus: function Change__updateStatus(str, state) {
this._updateStatusWithString(this._str(str), state);
},
_updateStatusWithString: function Change__updateStatusWithString(string, state) {
this._statusRow.hidden = false;
this._status.value = string;
this._statusIcon.setAttribute("status", state);
let error = state == "error";
this._dialog.getButton("cancel").disabled = !error;
this._dialog.getButton("finish").disabled = !error;
document.getElementById("printSyncKeyButton").disabled = !error;
document.getElementById("saveSyncKeyButton").disabled = !error;
if (state == "success")
window.setTimeout(window.close, 1500);
},
onDialogAccept() {
switch (this._dialogType) {
case "UpdatePassphrase":
case "ResetPassphrase":
return this.doChangePassphrase();
case "ChangePassword":
return this.doChangePassword();
}
return undefined;
},
doGeneratePassphrase() {
let passphrase = Weave.Utils.generatePassphrase();
this._passphraseBox.value = Weave.Utils.hyphenatePassphrase(passphrase);
this._dialog.getButton("finish").disabled = false;
},
doChangePassphrase: function Change_doChangePassphrase() {
let pp = Weave.Utils.normalizePassphrase(this._passphraseBox.value);
if (this._updatingPassphrase) {
Weave.Service.identity.syncKey = pp;
if (Weave.Service.login()) {
this._updateStatus("change.recoverykey.success", "success");
Weave.Service.persistLogin();
Weave.Service.scheduler.delayedAutoConnect(0);
} else {
this._updateStatus("new.passphrase.status.incorrect", "error");
}
} else {
this._updateStatus("change.recoverykey.label", "active");
if (Weave.Service.changePassphrase(pp))
this._updateStatus("change.recoverykey.success", "success");
else
this._updateStatus("change.recoverykey.error", "error");
}
return false;
},
doChangePassword: function Change_doChangePassword() {
if (this._currentPasswordInvalid) {
Weave.Service.identity.basicPassword = this._firstBox.value;
if (Weave.Service.login()) {
this._updateStatus("change.password.status.success", "success");
Weave.Service.persistLogin();
} else {
this._updateStatus("new.password.status.incorrect", "error");
}
} else {
this._updateStatus("change.password.status.active", "active");
if (Weave.Service.changePassword(this._firstBox.value))
this._updateStatus("change.password.status.success", "success");
else
this._updateStatus("change.password.status.error", "error");
}
return false;
},
validate(event) {
let valid = false;
let errorString = "";
if (this._dialogType == "ChangePassword") {
if (this._currentPasswordInvalid)
[valid, errorString] = gSyncUtils.validatePassword(this._firstBox);
else
[valid, errorString] = gSyncUtils.validatePassword(this._firstBox, this._secondBox);
} else {
if (!this._updatingPassphrase)
return;
valid = this._passphraseBox.value != "";
}
if (errorString == "")
this._clearStatus();
else
this._updateStatusWithString(errorString, "error");
this._statusRow.hidden = valid;
this._dialog.getButton("finish").disabled = !valid;
},
_str: function Change__string(str) {
return this._stringBundle.GetStringFromName(str);
}
};

View File

@ -0,0 +1,123 @@
<?xml version="1.0"?>
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<?xml-stylesheet href="chrome://browser/skin/syncSetup.css" type="text/css"?>
<?xml-stylesheet href="chrome://browser/skin/syncCommon.css" type="text/css"?>
<!DOCTYPE window [
<!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
<!ENTITY % syncBrandDTD SYSTEM "chrome://browser/locale/syncBrand.dtd">
<!ENTITY % syncSetupDTD SYSTEM "chrome://browser/locale/syncSetup.dtd">
%brandDTD;
%syncBrandDTD;
%syncSetupDTD;
]>
<wizard xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:html="http://www.w3.org/1999/xhtml"
id="change-dialog"
windowtype="Weave:ChangeSomething"
persist="screenX screenY"
onwizardnext="Change.onLoad()"
onwizardfinish="return Change.onDialogAccept();">
<script type="application/javascript"
src="chrome://browser/content/sync/genericChange.js"/>
<script type="application/javascript"
src="chrome://browser/content/sync/utils.js"/>
<script type="application/javascript"
src="chrome://global/content/printUtils.js"/>
<wizardpage id="change-page"
label="">
<description id="introText">
</description>
<separator class="thin"/>
<groupbox>
<grid>
<columns>
<column align="right"/>
<column flex="3"/>
<column flex="1"/>
</columns>
<rows>
<row id="textBox1Row" align="center">
<label id="textBox1Label" control="textBox1"/>
<textbox id="textBox1" type="password" oninput="Change.validate()"/>
<spacer/>
</row>
<row id="textBox2Row" align="center">
<label id="textBox2Label" control="textBox2"/>
<textbox id="textBox2" type="password" oninput="Change.validate()"/>
<spacer/>
</row>
</rows>
</grid>
<vbox id="passphraseRow">
<hbox flex="1">
<label id="passphraseLabel" control="passphraseBox"/>
<spacer flex="1"/>
<label id="generatePassphraseButton"
hidden="true"
value="&syncGenerateNewKey.label;"
class="text-link"
onclick="event.stopPropagation();
Change.doGeneratePassphrase();"/>
</hbox>
<textbox id="passphraseBox"
flex="1"
onfocus="this.select()"
oninput="Change.validate()"/>
</vbox>
<vbox id="feedback" pack="center">
<hbox id="statusRow" align="center">
<image id="statusIcon" class="statusIcon"/>
<label id="status" class="status" value=" "/>
</hbox>
</vbox>
</groupbox>
<separator class="thin"/>
<hbox id="passphraseBackupButtons"
hidden="true"
pack="center">
<button id="printSyncKeyButton"
label="&button.syncKeyBackup.print.label;"
accesskey="&button.syncKeyBackup.print.accesskey;"
oncommand="gSyncUtils.passphrasePrint('passphraseBox');"/>
<button id="saveSyncKeyButton"
label="&button.syncKeyBackup.save.label;"
accesskey="&button.syncKeyBackup.save.accesskey;"
oncommand="gSyncUtils.passphraseSave('passphraseBox');"/>
</hbox>
<vbox id="passphraseHelpBox"
hidden="true">
<description>
&existingRecoveryKey.description;
<label class="text-link"
href="https://services.mozilla.com/sync/help/manual-setup">
&addDevice.showMeHow.label;
</label>
</description>
</vbox>
<spacer id="passphraseSpacer"
flex="1"
hidden="true"/>
<description id="warningText" class="data">
</description>
<spacer flex="1"/>
</wizardpage>
</wizard>

View File

@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<!DOCTYPE html [
<!ENTITY % htmlDTD PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
%htmlDTD;
<!ENTITY % syncBrandDTD SYSTEM "chrome://browser/locale/syncBrand.dtd">
%syncBrandDTD;
<!ENTITY % syncKeyDTD SYSTEM "chrome://browser/locale/syncKey.dtd">
%syncKeyDTD;
<!ENTITY % globalDTD SYSTEM "chrome://global/locale/global.dtd" >
%globalDTD;
]>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>&syncKey.page.title;</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="robots" content="noindex"/>
<style type="text/css">
#synckey { font-size: 150% }
footer { font-size: 70% }
/* Bug 575675: Need to have an a:visited rule in a chrome document. */
a:visited { color: purple; }
</style>
</head>
<body dir="&locale.dir;">
<h1>&syncKey.page.title;</h1>
<p id="synckey" dir="ltr">SYNCKEY</p>
<p>&syncKey.page.description2;</p>
<div id="column1">
<h2>&syncKey.keepItSecret.heading;</h2>
<p>&syncKey.keepItSecret.description;</p>
</div>
<div id="column2">
<h2>&syncKey.keepItSafe.heading;</h2>
<p><em>&syncKey.keepItSafe1.description;</em>&syncKey.keepItSafe2.description;<em>&syncKey.keepItSafe3.description;</em>&syncKey.keepItSafe4a.description;</p>
</div>
<p>&syncKey.findOutMore1.label;<a href="https://services.mozilla.com">https://services.mozilla.com</a>&syncKey.findOutMore2.label;</p>
<footer>
&syncKey.footer1.label;<a id="tosLink" href="termsURL">termsURL</a>&syncKey.footer2.label;<a id="ppLink" href="privacyURL">privacyURL</a>&syncKey.footer3.label;
</footer>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,490 @@
<?xml version="1.0"?>
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<?xml-stylesheet href="chrome://browser/skin/syncSetup.css" type="text/css"?>
<?xml-stylesheet href="chrome://browser/skin/syncCommon.css" type="text/css"?>
<!DOCTYPE window [
<!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
<!ENTITY % syncBrandDTD SYSTEM "chrome://browser/locale/syncBrand.dtd">
<!ENTITY % syncSetupDTD SYSTEM "chrome://browser/locale/syncSetup.dtd">
%brandDTD;
%syncBrandDTD;
%syncSetupDTD;
]>
<wizard id="wizard"
title="&accountSetupTitle.label;"
windowtype="Weave:AccountSetup"
persist="screenX screenY"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:html="http://www.w3.org/1999/xhtml"
onwizardnext="return gSyncSetup.onWizardAdvance()"
onwizardback="return gSyncSetup.onWizardBack()"
onwizardcancel="gSyncSetup.onWizardCancel()"
onload="gSyncSetup.init()">
<script type="application/javascript"
src="chrome://browser/content/sync/setup.js"/>
<script type="application/javascript"
src="chrome://browser/content/sync/utils.js"/>
<script type="application/javascript"
src="chrome://browser/content/utilityOverlay.js"/>
<script type="application/javascript"
src="chrome://global/content/printUtils.js"/>
<wizardpage id="addDevicePage"
label="&pairDevice.title.label;"
onpageshow="gSyncSetup.onPageShow()">
<description>
&pairDevice.dialog.description.label;
<label class="text-link"
value="&addDevice.showMeHow.label;"
href="https://services.mozilla.com/sync/help/add-device"/>
</description>
<separator class="groove-thin"/>
<description>
&addDevice.dialog.enterCode.label;
</description>
<separator class="groove-thin"/>
<vbox align="center">
<textbox id="pin1"
class="pin"
oninput="gSyncSetup.onPINInput(this);"
onfocus="this.select();"
/>
<textbox id="pin2"
class="pin"
oninput="gSyncSetup.onPINInput(this);"
onfocus="this.select();"
/>
<textbox id="pin3"
class="pin"
oninput="gSyncSetup.onPINInput(this);"
onfocus="this.select();"
/>
</vbox>
<separator class="groove-thin"/>
<vbox id="pairDeviceThrobber" align="center" hidden="true">
<image/>
</vbox>
<hbox id="pairDeviceErrorRow" pack="center" hidden="true">
<image class="statusIcon" status="error"/>
<label class="status"
value="&addDevice.dialog.tryAgain.label;"/>
</hbox>
</wizardpage>
<wizardpage id="pickSetupType"
label="&syncBrand.fullName.label;"
onpageshow="gSyncSetup.onPageShow()">
<vbox align="center" flex="1">
<description style="padding: 0 7em;">
&setup.pickSetupType.description2;
</description>
<spacer flex="3"/>
<button id="newAccount"
class="accountChoiceButton"
label="&button.createNewAccount.label;"
oncommand="gSyncSetup.startNewAccountSetup()"
align="center"/>
<spacer flex="1"/>
</vbox>
<separator class="groove"/>
<vbox align="center" flex="1">
<spacer flex="1"/>
<button id="existingAccount"
class="accountChoiceButton"
label="&button.haveAccount.label;"
oncommand="gSyncSetup.useExistingAccount()"/>
<spacer flex="3"/>
</vbox>
</wizardpage>
<wizardpage label="&setup.newAccountDetailsPage.title.label;"
id="newAccountStart"
onextra1="gSyncSetup.onSyncOptions()"
onpageshow="gSyncSetup.onPageShow();">
<grid>
<columns>
<column/>
<column class="inputColumn" flex="1"/>
</columns>
<rows>
<row id="emailRow" align="center">
<label value="&setup.emailAddress.label;"
accesskey="&setup.emailAddress.accesskey;"
control="weaveEmail"/>
<textbox id="weaveEmail"
oninput="gSyncSetup.onEmailInput()"/>
</row>
<row id="emailFeedbackRow" align="center" hidden="true">
<spacer/>
<hbox>
<image class="statusIcon"/>
<label class="status" value=" "/>
</hbox>
</row>
<row id="passwordRow" align="center">
<label value="&setup.choosePassword.label;"
accesskey="&setup.choosePassword.accesskey;"
control="weavePassword"/>
<textbox id="weavePassword"
type="password"
onchange="gSyncSetup.onPasswordChange()"/>
</row>
<row id="confirmRow" align="center">
<label value="&setup.confirmPassword.label;"
accesskey="&setup.confirmPassword.accesskey;"
control="weavePasswordConfirm"/>
<textbox id="weavePasswordConfirm"
type="password"
onchange="gSyncSetup.onPasswordChange()"/>
</row>
<row id="passwordFeedbackRow" align="center" hidden="true">
<spacer/>
<hbox>
<image class="statusIcon"/>
<label class="status" value=" "/>
</hbox>
</row>
<row align="center">
<label control="server"
value="&server.label;"/>
<menulist id="server"
oncommand="gSyncSetup.onServerCommand()"
oninput="gSyncSetup.onServerInput()">
<menupopup>
<menuitem label="&serverType.default.label;"
value="main"/>
<menuitem label="&serverType.custom2.label;"
value="custom"/>
</menupopup>
</menulist>
</row>
<row id="serverFeedbackRow" align="center" hidden="true">
<spacer/>
<hbox>
<image class="statusIcon"/>
<label class="status" value=" "/>
</hbox>
</row>
<row id="TOSRow" align="center">
<spacer/>
<hbox align="center">
<checkbox id="tos"
accesskey="&setup.tosAgree1.accesskey;"
oncommand="this.focus(); gSyncSetup.checkFields();"/>
<description id="tosDesc"
flex="1"
onclick="document.getElementById('tos').focus();
document.getElementById('tos').click()">
&setup.tosAgree1.label;
<label class="text-link"
onclick="event.stopPropagation();gSyncUtils.openToS();">
&setup.tosLink.label;
</label>
&setup.tosAgree2.label;
<label class="text-link"
onclick="event.stopPropagation();gSyncUtils.openPrivacyPolicy();">
&setup.ppLink.label;
</label>
&setup.tosAgree3.label;
</description>
</hbox>
</row>
</rows>
</grid>
<spacer flex="1"/>
<vbox flex="1" align="center">
<browser height="150"
width="500"
id="captcha"
type="content"
disablehistory="true"/>
<spacer flex="1"/>
<hbox id="captchaFeedback">
<image class="statusIcon"/>
<label class="status" value=" "/>
</hbox>
</vbox>
</wizardpage>
<wizardpage id="addDevice"
label="&pairDevice.title.label;"
onextra1="gSyncSetup.onSyncOptions()"
onpageshow="gSyncSetup.onPageShow()">
<description>
&pairDevice.setup.description.label;
<label class="text-link"
value="&addDevice.showMeHow.label;"
href="https://services.mozilla.com/sync/help/easy-setup"/>
</description>
<label value="&addDevice.setup.enterCode.label;"
control="easySetupPIN1"/>
<spacer flex="1"/>
<vbox align="center" flex="1">
<textbox id="easySetupPIN1"
class="pin"
value=""
readonly="true"
/>
<textbox id="easySetupPIN2"
class="pin"
value=""
readonly="true"
/>
<textbox id="easySetupPIN3"
class="pin"
value=""
readonly="true"
/>
</vbox>
<spacer flex="3"/>
<label class="text-link"
value="&addDevice.dontHaveDevice.label;"
onclick="gSyncSetup.manualSetup();"/>
</wizardpage>
<wizardpage id="existingAccount"
label="&setup.signInPage.title.label;"
onextra1="gSyncSetup.onSyncOptions()"
onpageshow="gSyncSetup.onPageShow()">
<grid>
<columns>
<column/>
<column class="inputColumn" flex="1"/>
</columns>
<rows>
<row id="existingAccountRow" align="center">
<label id="existingAccountLabel"
value="&signIn.account2.label;"
accesskey="&signIn.account2.accesskey;"
control="existingAccount"/>
<textbox id="existingAccountName"
oninput="gSyncSetup.checkFields(event)"
onchange="gSyncSetup.checkFields(event)"/>
</row>
<row id="existingPasswordRow" align="center">
<label id="existingPasswordLabel"
value="&signIn.password.label;"
accesskey="&signIn.password.accesskey;"
control="existingPassword"/>
<textbox id="existingPassword"
type="password"
onkeyup="gSyncSetup.checkFields(event)"
onchange="gSyncSetup.checkFields(event)"/>
</row>
<row id="existingPasswordFeedbackRow" align="center" hidden="true">
<spacer/>
<hbox>
<image class="statusIcon"/>
<label class="status" value=" "/>
</hbox>
</row>
<row align="center">
<spacer/>
<label class="text-link"
value="&resetPassword.label;"
onclick="gSyncUtils.resetPassword(); return false;"/>
</row>
<row align="center">
<label control="existingServer"
value="&server.label;"/>
<menulist id="existingServer"
oncommand="gSyncSetup.onExistingServerCommand()"
oninput="gSyncSetup.onExistingServerInput()">
<menupopup>
<menuitem label="&serverType.default.label;"
value="main"/>
<menuitem label="&serverType.custom2.label;"
value="custom"/>
</menupopup>
</menulist>
</row>
<row id="existingServerFeedbackRow" align="center" hidden="true">
<spacer/>
<hbox>
<image class="statusIcon"/>
<vbox>
<label class="status" value=" "/>
</vbox>
</hbox>
</row>
</rows>
</grid>
<groupbox>
<label id="existingPassphraseLabel"
value="&signIn.recoveryKey.label;"
accesskey="&signIn.recoveryKey.accesskey;"
control="existingPassphrase"/>
<textbox id="existingPassphrase"
oninput="gSyncSetup.checkFields()"/>
<hbox id="login-throbber" hidden="true">
<image/>
<label value="&verifying.label;"/>
</hbox>
<vbox align="left" id="existingPassphraseFeedbackRow" hidden="true">
<hbox>
<image class="statusIcon"/>
<label class="status" value=" "/>
</hbox>
</vbox>
</groupbox>
<vbox id="passphraseHelpBox">
<description>
&existingRecoveryKey.description;
<label class="text-link"
href="https://services.mozilla.com/sync/help/manual-setup">
&addDevice.showMeHow.label;
</label>
<spacer id="passphraseHelpSpacer"/>
<label class="text-link"
onclick="gSyncSetup.resetPassphrase(); return false;">
&resetSyncKey.label;
</label>
</description>
</vbox>
</wizardpage>
<wizardpage id="syncOptionsPage"
label="&setup.optionsPage.title;"
onpageshow="gSyncSetup.onPageShow()">
<groupbox id="syncOptions">
<grid>
<columns>
<column/>
<column flex="1" style="margin-inline-end: 2px"/>
</columns>
<rows>
<row align="center">
<label value="&syncDeviceName.label;"
accesskey="&syncDeviceName.accesskey;"
control="syncComputerName"/>
<textbox id="syncComputerName" flex="1"
onchange="gSyncUtils.changeName(this)"/>
</row>
<row>
<label value="&syncMy.label;" />
<vbox>
<checkbox label="&engine.addons.label;"
accesskey="&engine.addons.accesskey;"
id="engine.addons"
checked="true"/>
<checkbox label="&engine.bookmarks.label;"
accesskey="&engine.bookmarks.accesskey;"
id="engine.bookmarks"
checked="true"/>
<checkbox label="&engine.passwords.label;"
accesskey="&engine.passwords.accesskey;"
id="engine.passwords"
checked="true"/>
<checkbox label="&engine.prefs.label;"
accesskey="&engine.prefs.accesskey;"
id="engine.prefs"
checked="true"/>
<checkbox label="&engine.history.label;"
accesskey="&engine.history.accesskey;"
id="engine.history"
checked="true"/>
<checkbox label="&engine.tabs.label2;"
accesskey="&engine.tabs.accesskey;"
id="engine.tabs"
checked="true"/>
</vbox>
</row>
</rows>
</grid>
</groupbox>
<groupbox id="mergeOptions">
<radiogroup id="mergeChoiceRadio" pack="start">
<grid>
<columns>
<column/>
<column flex="1"/>
</columns>
<rows flex="1">
<row align="center">
<radio id="resetClient"
class="mergeChoiceButton"
aria-labelledby="resetClientLabel"/>
<label id="resetClientLabel" control="resetClient">
<html:strong>&choice2.merge.recommended.label;</html:strong>
&choice2a.merge.main.label;
</label>
</row>
<row align="center">
<radio id="wipeClient"
class="mergeChoiceButton"
aria-labelledby="wipeClientLabel"/>
<label id="wipeClientLabel"
control="wipeClient">
&choice2a.client.main.label;
</label>
</row>
<row align="center">
<radio id="wipeRemote"
class="mergeChoiceButton"
aria-labelledby="wipeRemoteLabel"/>
<label id="wipeRemoteLabel"
control="wipeRemote">
&choice2a.server.main.label;
</label>
</row>
</rows>
</grid>
</radiogroup>
</groupbox>
</wizardpage>
<wizardpage id="syncOptionsConfirm"
label="&setup.optionsConfirmPage.title;"
onpageshow="gSyncSetup.onPageShow()">
<deck id="chosenActionDeck">
<vbox id="chosenActionMerge" class="confirm">
<description class="normal">
&confirm.merge2.label;
</description>
</vbox>
<vbox id="chosenActionWipeClient" class="confirm">
<description class="normal">
&confirm.client3.label;
</description>
<separator class="thin"/>
<vbox id="dataList">
<label class="data indent" id="bookmarkCount"/>
<label class="data indent" id="historyCount"/>
<label class="data indent" id="passwordCount"/>
<label class="data indent" id="addonCount"/>
<label class="data indent" id="prefsWipe"
value="&engine.prefs.label;"/>
</vbox>
<separator class="thin"/>
<description class="normal">
&confirm.client2.moreinfo.label;
</description>
</vbox>
<vbox id="chosenActionWipeServer" class="confirm">
<description class="normal">
&confirm.server2.label;
</description>
<separator class="thin"/>
<vbox id="clientList">
</vbox>
</vbox>
</deck>
</wizardpage>
<!-- In terms of the wizard flow shown to the user, the 'syncOptionsConfirm'
page above is not the last wizard page. To prevent the wizard binding from
assuming that it is, we're inserting this dummy page here. This also means
that the wizard needs to always be closed manually via wizardFinish(). -->
<wizardpage>
</wizardpage>
</wizard>

View File

@ -0,0 +1,229 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Equivalent to 0o600 permissions; used for saved Sync Recovery Key.
// This constant can be replaced when the equivalent values are available to
// chrome JS; see Bug 433295 and Bug 757351.
const PERMISSIONS_RWUSR = 0x180;
// Weave should always exist before before this file gets included.
var gSyncUtils = {
get bundle() {
delete this.bundle;
return this.bundle = Services.strings.createBundle("chrome://browser/locale/syncSetup.properties");
},
get fxAccountsEnabled() {
let service = Components.classes["@mozilla.org/weave/service;1"]
.getService(Components.interfaces.nsISupports)
.wrappedJSObject;
return service.fxAccountsEnabled;
},
// opens in a new window if we're in a modal prefwindow world, in a new tab otherwise
_openLink(url) {
let thisDocEl = document.documentElement,
openerDocEl = window.opener && window.opener.document.documentElement;
if (thisDocEl.id == "accountSetup" && window.opener &&
openerDocEl.id == "BrowserPreferences" && !openerDocEl.instantApply)
openUILinkIn(url, "window");
else if (thisDocEl.id == "BrowserPreferences" && !thisDocEl.instantApply)
openUILinkIn(url, "window");
else if (document.documentElement.id == "change-dialog")
Services.wm.getMostRecentWindow("navigator:browser")
.openUILinkIn(url, "tab");
else
openUILinkIn(url, "tab");
},
changeName: function changeName(input) {
// Make sure to update to a modified name, e.g., empty-string -> default
Weave.Service.clientsEngine.localName = input.value;
input.value = Weave.Service.clientsEngine.localName;
},
openChange: function openChange(type, duringSetup) {
// Just re-show the dialog if it's already open
let openedDialog = Services.wm.getMostRecentWindow("Sync:" + type);
if (openedDialog != null) {
openedDialog.focus();
return;
}
// Open up the change dialog
let changeXUL = "chrome://browser/content/sync/genericChange.xul";
let changeOpt = "centerscreen,chrome,resizable=no";
Services.ww.activeWindow.openDialog(changeXUL, "", changeOpt,
type, duringSetup);
},
changePassword() {
if (Weave.Utils.ensureMPUnlocked())
this.openChange("ChangePassword");
},
resetPassphrase(duringSetup) {
if (Weave.Utils.ensureMPUnlocked())
this.openChange("ResetPassphrase", duringSetup);
},
updatePassphrase() {
if (Weave.Utils.ensureMPUnlocked())
this.openChange("UpdatePassphrase");
},
resetPassword() {
this._openLink(Weave.Service.pwResetURL);
},
get tosURL() {
let root = this.fxAccountsEnabled ? "fxa." : "";
return Weave.Svc.Prefs.get(root + "termsURL");
},
openToS() {
this._openLink(this.tosURL);
},
get privacyPolicyURL() {
let root = this.fxAccountsEnabled ? "fxa." : "";
return Weave.Svc.Prefs.get(root + "privacyURL");
},
openPrivacyPolicy() {
this._openLink(this.privacyPolicyURL);
},
/**
* Prepare an invisible iframe with the passphrase backup document.
* Used by both the print and saving methods.
*
* @param elid : ID of the form element containing the passphrase.
* @param callback : Function called once the iframe has loaded.
*/
_preparePPiframe(elid, callback) {
let pp = document.getElementById(elid).value;
// Create an invisible iframe whose contents we can print.
let iframe = document.createElement("iframe");
iframe.setAttribute("src", "chrome://browser/content/sync/key.xhtml");
iframe.collapsed = true;
document.documentElement.appendChild(iframe);
iframe.contentWindow.addEventListener("load", function() {
// Insert the Sync Key into the page.
let el = iframe.contentDocument.getElementById("synckey");
el.firstChild.nodeValue = pp;
// Insert the TOS and Privacy Policy URLs into the page.
let termsURL = Weave.Svc.Prefs.get("termsURL");
el = iframe.contentDocument.getElementById("tosLink");
el.setAttribute("href", termsURL);
el.firstChild.nodeValue = termsURL;
let privacyURL = Weave.Svc.Prefs.get("privacyURL");
el = iframe.contentDocument.getElementById("ppLink");
el.setAttribute("href", privacyURL);
el.firstChild.nodeValue = privacyURL;
callback(iframe);
}, {once: true});
},
/**
* Print passphrase backup document.
*
* @param elid : ID of the form element containing the passphrase.
*/
passphrasePrint(elid) {
this._preparePPiframe(elid, function(iframe) {
let webBrowserPrint = iframe.contentWindow
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebBrowserPrint);
let printSettings = PrintUtils.getPrintSettings();
// Display no header/footer decoration except for the date.
printSettings.headerStrLeft
= printSettings.headerStrCenter
= printSettings.headerStrRight
= printSettings.footerStrLeft
= printSettings.footerStrCenter = "";
printSettings.footerStrRight = "&D";
try {
webBrowserPrint.print(printSettings, null);
} catch (ex) {
// print()'s return codes are expressed as exceptions. Ignore.
}
});
},
/**
* Save passphrase backup document to disk as HTML file.
*
* @param elid : ID of the form element containing the passphrase.
*/
passphraseSave(elid) {
let dialogTitle = this.bundle.GetStringFromName("save.recoverykey.title");
let defaultSaveName = this.bundle.GetStringFromName("save.recoverykey.defaultfilename");
this._preparePPiframe(elid, function(iframe) {
let fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
let fpCallback = function fpCallback_done(aResult) {
if (aResult == Ci.nsIFilePicker.returnOK ||
aResult == Ci.nsIFilePicker.returnReplace) {
let stream = Cc["@mozilla.org/network/file-output-stream;1"].
createInstance(Ci.nsIFileOutputStream);
stream.init(fp.file, -1, PERMISSIONS_RWUSR, 0);
let serializer = new XMLSerializer();
let output = serializer.serializeToString(iframe.contentDocument);
output = output.replace(/<!DOCTYPE (.|\n)*?]>/,
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ' +
'"DTD/xhtml1-strict.dtd">');
output = Weave.Utils.encodeUTF8(output);
stream.write(output, output.length);
}
};
fp.init(window, dialogTitle, Ci.nsIFilePicker.modeSave);
fp.appendFilters(Ci.nsIFilePicker.filterHTML);
fp.defaultString = defaultSaveName;
fp.open(fpCallback);
return false;
});
},
/**
* validatePassword
*
* @param el1 : the first textbox element in the form
* @param el2 : the second textbox element, if omitted it's an update form
*
* returns [valid, errorString]
*/
validatePassword(el1, el2) {
let valid = false;
let val1 = el1.value;
let val2 = el2 ? el2.value : "";
let error = "";
if (!el2)
valid = val1.length >= Weave.MIN_PASS_LENGTH;
else if (val1 && val1 == Weave.Service.identity.username)
error = "change.password.pwSameAsUsername";
else if (val1 && val1 == Weave.Service.identity.account)
error = "change.password.pwSameAsEmail";
else if (val1 && val1 == Weave.Service.identity.basicPassword)
error = "change.password.pwSameAsPassword";
else if (val1 && val2) {
if (val1 == val2 && val1.length >= Weave.MIN_PASS_LENGTH)
valid = true;
else if (val1.length < Weave.MIN_PASS_LENGTH)
error = "change.password.tooShort";
else if (val1 != val2)
error = "change.password.mismatch";
}
let errorString = error ? Weave.Utils.getErrorString(error) : "";
return [valid, errorString];
}
};

View File

@ -318,6 +318,7 @@ tags = fullscreen
skip-if = os == "linux" # Linux: Intermittent failures - bug 941575.
[browser_fxaccounts.js]
support-files = fxa_profile_handler.sjs
[browser_fxa_migrate.js]
[browser_fxa_web_channel.js]
[browser_gestureSupport.js]
skip-if = e10s # Bug 863514 - no gesture support.

View File

@ -0,0 +1,18 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
const STATE_CHANGED_TOPIC = "fxa-migration:state-changed";
const NOTIFICATION_TITLE = "fxa-migration";
var imports = {};
Cu.import("resource://services-sync/FxaMigrator.jsm", imports);
add_task(function* test() {
// Fake the state where we saw an EOL notification.
Services.obs.notifyObservers(null, STATE_CHANGED_TOPIC, null);
let notificationBox = document.getElementById("global-notificationbox");
Assert.ok(notificationBox.allNotifications.some(n => {
return n.getAttribute("value") == NOTIFICATION_TITLE;
}), "Disconnect notification should be present");
});

View File

@ -16,9 +16,9 @@ const TEST_ROOT = "http://example.com/browser/browser/base/content/test/general/
// The stub functions.
let stubs = {
updateUI() {
return unstubs["updateUI"].call(gFxAccounts).then(() => {
Services.obs.notifyObservers(null, "test:browser_fxaccounts:updateUI", null);
updateAppMenuItem() {
return unstubs["updateAppMenuItem"].call(gFxAccounts).then(() => {
Services.obs.notifyObservers(null, "test:browser_fxaccounts:updateAppMenuItem", null);
});
},
// Opening preferences is trickier than it should be as leaks are reported
@ -72,7 +72,7 @@ var panelUIFooter = document.getElementById("PanelUI-footer-fxa");
add_task(function* test_nouser() {
let user = yield fxAccounts.getSignedInUser();
Assert.strictEqual(user, null, "start with no user signed in");
let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateUI");
let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateAppMenuItem");
Services.obs.notifyObservers(null, this.FxAccountsCommon.ONLOGOUT_NOTIFICATION, null);
yield promiseUpdateDone;
@ -93,7 +93,7 @@ add_task(function* test_nouser() {
XXX - Bug 1191162 - need a better hawk mock story or this will leak in debug builds.
add_task(function* test_unverifiedUser() {
let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateUI");
let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateAppMenuItem");
yield setSignedInUser(false); // this will fire the observer that does the update.
yield promiseUpdateDone;
@ -112,10 +112,10 @@ add_task(function* test_unverifiedUser() {
*/
add_task(function* test_verifiedUserEmptyProfile() {
// We see 2 updateUI() calls - one for the signedInUser and one after
// We see 2 updateAppMenuItem() calls - one for the signedInUser and one after
// we first fetch the profile. We want them both to fire or we aren't testing
// the state we think we are testing.
let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateUI", 2);
let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateAppMenuItem", 2);
configureProfileURL({}); // successful but empty profile.
yield setSignedInUser(true); // this will fire the observer that does the update.
yield promiseUpdateDone;
@ -134,7 +134,7 @@ add_task(function* test_verifiedUserEmptyProfile() {
});
add_task(function* test_verifiedUserDisplayName() {
let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateUI", 2);
let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateAppMenuItem", 2);
configureProfileURL({ displayName: "Test User Display Name" });
yield setSignedInUser(true); // this will fire the observer that does the update.
yield promiseUpdateDone;
@ -149,7 +149,7 @@ add_task(function* test_verifiedUserDisplayName() {
add_task(function* test_verifiedUserProfileFailure() {
// profile failure means only one observer fires.
let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateUI", 1);
let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateAppMenuItem", 1);
configureProfileURL(null, 500);
yield setSignedInUser(true); // this will fire the observer that does the update.
yield promiseUpdateDone;
@ -250,7 +250,7 @@ var signOut = Task.async(function* () {
// This test needs to make sure that any updates for the logout have
// completed before starting the next test, or we see the observer
// notifications get out of sync.
let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateUI");
let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateAppMenuItem");
// we always want a "localOnly" signout here...
yield fxAccounts.signOut(true);
yield promiseUpdateDone;

View File

@ -139,6 +139,17 @@ browser.jar:
content/browser/sync/aboutSyncTabs.js (content/sync/aboutSyncTabs.js)
content/browser/sync/aboutSyncTabs.css (content/sync/aboutSyncTabs.css)
content/browser/sync/aboutSyncTabs-bindings.xml (content/sync/aboutSyncTabs-bindings.xml)
content/browser/sync/setup.xul (content/sync/setup.xul)
content/browser/sync/addDevice.js (content/sync/addDevice.js)
content/browser/sync/addDevice.xul (content/sync/addDevice.xul)
content/browser/sync/setup.js (content/sync/setup.js)
content/browser/sync/genericChange.xul (content/sync/genericChange.xul)
content/browser/sync/genericChange.js (content/sync/genericChange.js)
content/browser/sync/key.xhtml (content/sync/key.xhtml)
content/browser/sync/utils.js (content/sync/utils.js)
* content/browser/sync/customize.xul (content/sync/customize.xul)
content/browser/sync/customize.js (content/sync/customize.js)
content/browser/sync/customize.css (content/sync/customize.css)
content/browser/safeMode.css (content/safeMode.css)
content/browser/safeMode.js (content/safeMode.js)
content/browser/safeMode.xul (content/safeMode.xul)

View File

@ -138,7 +138,7 @@
<hbox pack="center">
<toolbarbutton class="PanelUI-remotetabs-prefs-button"
label="&appMenuRemoteTabs.openprefs.label;"
oncommand="gSyncUI.openPrefs('synced-tabs');"/>
oncommand="gSyncUI.openSetup(null, 'synced-tabs');"/>
</hbox>
</vbox>
</hbox>
@ -172,7 +172,7 @@
<label class="PanelUI-remotetabs-instruction-label">&appMenuRemoteTabs.notsignedin.label;</label>
<toolbarbutton class="PanelUI-remotetabs-prefs-button"
label="&appMenuRemoteTabs.signin.label;"
oncommand="gSyncUI.openPrefs('synced-tabs');"/>
oncommand="gSyncUI.openSetup(null, 'synced-tabs');"/>
</vbox>
<!-- When Sync needs re-authentication. This uses the exact same messaging
as "Sync is not configured" but remains a separate box so we get
@ -186,7 +186,7 @@
<label class="PanelUI-remotetabs-instruction-label">&appMenuRemoteTabs.notsignedin.label;</label>
<toolbarbutton class="PanelUI-remotetabs-prefs-button"
label="&appMenuRemoteTabs.signin.label;"
oncommand="gSyncUI.openPrefs('synced-tabs');"/>
oncommand="gSyncUI.openSetup(null, 'synced-tabs');"/>
</vbox>
</hbox>
</vbox>

View File

@ -12,8 +12,11 @@ XPCOMUtils.defineLazyGetter(this, "FxAccountsCommon", function() {
XPCOMUtils.defineLazyModuleGetter(this, "fxAccounts",
"resource://gre/modules/FxAccounts.jsm");
const FXA_PAGE_LOGGED_OUT = 0;
const FXA_PAGE_LOGGED_IN = 1;
const PAGE_NO_ACCOUNT = 0;
const PAGE_HAS_ACCOUNT = 1;
const PAGE_NEEDS_UPDATE = 2;
const FXA_PAGE_LOGGED_OUT = 3;
const FXA_PAGE_LOGGED_IN = 4;
// Indexes into the "login status" deck.
// We are in a successful verified state - everything should work!
@ -35,6 +38,17 @@ var gSyncPane = {
document.getElementById("weavePrefsDeck").selectedIndex = val;
},
get _usingCustomServer() {
return Weave.Svc.Prefs.isSet("serverURL");
},
needsUpdate() {
this.page = PAGE_NEEDS_UPDATE;
let label = document.getElementById("loginError");
label.textContent = Weave.Utils.getErrorString(Weave.Status.login);
label.className = "error";
},
init() {
this._setupEventListeners();
@ -78,19 +92,20 @@ var gSyncPane = {
} catch (e) {}
if (!username) {
this.page = FXA_PAGE_LOGGED_OUT;
return;
} else if (xps.fxAccountsEnabled) {
// Use cached values while we wait for the up-to-date values
let cachedComputerName;
try {
cachedComputerName = Services.prefs.getCharPref("services.sync.client.name");
} catch (e) {
cachedComputerName = "";
}
document.getElementById("fxaEmailAddress1").textContent = username;
this._populateComputerName(cachedComputerName);
this.page = FXA_PAGE_LOGGED_IN;
} else { // Old Sync
this.page = PAGE_HAS_ACCOUNT;
}
// Use cached values while we wait for the up-to-date values
let cachedComputerName;
try {
cachedComputerName = Services.prefs.getCharPref("services.sync.client.name");
} catch (e) {
cachedComputerName = "";
}
document.getElementById("fxaEmailAddress1").textContent = username;
this._populateComputerName(cachedComputerName);
this.page = FXA_PAGE_LOGGED_IN;
},
_init() {
@ -116,6 +131,10 @@ var gSyncPane = {
}, gSyncPane);
});
XPCOMUtils.defineLazyGetter(this, "_stringBundle", () => {
return Services.strings.createBundle("chrome://browser/locale/preferences/preferences.properties");
});
XPCOMUtils.defineLazyGetter(this, "_accountsStringBundle", () => {
return Services.strings.createBundle("chrome://browser/locale/accounts.properties");
});
@ -127,8 +146,10 @@ var gSyncPane = {
document.getElementById("fxaMobilePromo-ios").setAttribute("href", url);
document.getElementById("fxaMobilePromo-ios-hasFxaAccount").setAttribute("href", url);
document.getElementById("tosPP-small-ToS").setAttribute("href", Weave.Svc.Prefs.get("fxa.termsURL"));
document.getElementById("tosPP-small-PP").setAttribute("href", Weave.Svc.Prefs.get("fxa.privacyURL"));
document.getElementById("tosPP-small-ToS").setAttribute("href", gSyncUtils.tosURL);
document.getElementById("tosPP-normal-ToS").setAttribute("href", gSyncUtils.tosURL);
document.getElementById("tosPP-small-PP").setAttribute("href", gSyncUtils.privacyPolicyURL);
document.getElementById("tosPP-normal-PP").setAttribute("href", gSyncUtils.privacyPolicyURL);
fxAccounts.promiseAccountsManageURI(this._getEntryPoint()).then(accountsManageURI => {
document.getElementById("verifiedManage").setAttribute("href", accountsManageURI);
@ -179,6 +200,30 @@ var gSyncPane = {
.addEventListener(aEventType, aCallback.bind(gSyncPane));
}
setEventListener("noAccountSetup", "click", function(aEvent) {
aEvent.stopPropagation();
gSyncPane.openSetup(null);
});
setEventListener("noAccountPair", "click", function(aEvent) {
aEvent.stopPropagation();
gSyncPane.openSetup("pair");
});
setEventListener("syncChangePassword", "command",
() => gSyncUtils.changePassword());
setEventListener("syncResetPassphrase", "command",
() => gSyncUtils.resetPassphrase());
setEventListener("syncReset", "command", gSyncPane.resetSync);
setEventListener("syncAddDeviceLabel", "click", function() {
gSyncPane.openAddDevice();
return false;
});
setEventListener("syncEnginesList", "select", function() {
if (this.selectedCount)
this.clearSelection();
});
setEventListener("syncComputerName", "change", function(e) {
gSyncUtils.changeName(e.target);
});
setEventListener("fxaChangeDeviceName", "command", function() {
this._toggleComputerNameControls(true);
this._focusComputerNameTextbox();
@ -200,6 +245,22 @@ var gSyncPane = {
this._updateComputerNameValue(true);
this._focusAfterComputerNameTextbox();
});
setEventListener("unlinkDevice", "click", function() {
gSyncPane.startOver(true);
return false;
});
setEventListener("loginErrorUpdatePass", "click", function() {
gSyncPane.updatePass();
return false;
});
setEventListener("loginErrorResetPass", "click", function() {
gSyncPane.resetPass();
return false;
});
setEventListener("loginErrorStartOver", "click", function() {
gSyncPane.startOver(true);
return false;
});
setEventListener("noFxaSignUp", "command", function() {
gSyncPane.signUp();
return false;
@ -243,104 +304,161 @@ var gSyncPane = {
let service = Components.classes["@mozilla.org/weave/service;1"]
.getService(Components.interfaces.nsISupports)
.wrappedJSObject;
// service.fxAccountsEnabled is false iff sync is already configured for
// the legacy provider.
if (service.fxAccountsEnabled) {
let displayNameLabel = document.getElementById("fxaDisplayName");
let fxaEmailAddress1Label = document.getElementById("fxaEmailAddress1");
fxaEmailAddress1Label.hidden = false;
displayNameLabel.hidden = true;
let displayNameLabel = document.getElementById("fxaDisplayName");
let fxaEmailAddress1Label = document.getElementById("fxaEmailAddress1");
fxaEmailAddress1Label.hidden = false;
displayNameLabel.hidden = true;
let profileInfoEnabled;
try {
profileInfoEnabled = Services.prefs.getBoolPref("identity.fxaccounts.profile_image.enabled");
} catch (ex) {}
let profileInfoEnabled;
try {
profileInfoEnabled = Services.prefs.getBoolPref("identity.fxaccounts.profile_image.enabled");
} catch (ex) {}
// determine the fxa status...
this._showLoadPage(service);
// determine the fxa status...
this._showLoadPage(service);
fxAccounts.getSignedInUser().then(data => {
if (!data) {
this.page = FXA_PAGE_LOGGED_OUT;
return false;
}
this.page = FXA_PAGE_LOGGED_IN;
// We are logged in locally, but maybe we are in a state where the
// server rejected our credentials (eg, password changed on the server)
let fxaLoginStatus = document.getElementById("fxaLoginStatus");
let syncReady;
// Not Verfied implies login error state, so check that first.
if (!data.verified) {
fxaLoginStatus.selectedIndex = FXA_LOGIN_UNVERIFIED;
syncReady = false;
// So we think we are logged in, so login problems are next.
// (Although if the Sync identity manager is still initializing, we
// ignore login errors and assume all will eventually be good.)
// LOGIN_FAILED_LOGIN_REJECTED explicitly means "you must log back in".
// All other login failures are assumed to be transient and should go
// away by themselves, so aren't reflected here.
} else if (Weave.Status.login == Weave.LOGIN_FAILED_LOGIN_REJECTED) {
fxaLoginStatus.selectedIndex = FXA_LOGIN_FAILED;
syncReady = false;
// Else we must be golden (or in an error state we expect to magically
// resolve itself)
} else {
fxaLoginStatus.selectedIndex = FXA_LOGIN_VERIFIED;
syncReady = true;
}
fxaEmailAddress1Label.textContent = data.email;
document.getElementById("fxaEmailAddress2").textContent = data.email;
document.getElementById("fxaEmailAddress3").textContent = data.email;
this._populateComputerName(Weave.Service.clientsEngine.localName);
let engines = document.getElementById("fxaSyncEngines")
for (let checkbox of engines.querySelectorAll("checkbox")) {
checkbox.disabled = !syncReady;
}
document.getElementById("fxaChangeDeviceName").disabled = !syncReady;
fxAccounts.getSignedInUser().then(data => {
if (!data) {
this.page = FXA_PAGE_LOGGED_OUT;
return false;
}
this.page = FXA_PAGE_LOGGED_IN;
// We are logged in locally, but maybe we are in a state where the
// server rejected our credentials (eg, password changed on the server)
let fxaLoginStatus = document.getElementById("fxaLoginStatus");
let syncReady;
// Not Verfied implies login error state, so check that first.
if (!data.verified) {
fxaLoginStatus.selectedIndex = FXA_LOGIN_UNVERIFIED;
syncReady = false;
// So we think we are logged in, so login problems are next.
// (Although if the Sync identity manager is still initializing, we
// ignore login errors and assume all will eventually be good.)
// LOGIN_FAILED_LOGIN_REJECTED explicitly means "you must log back in".
// All other login failures are assumed to be transient and should go
// away by themselves, so aren't reflected here.
} else if (Weave.Status.login == Weave.LOGIN_FAILED_LOGIN_REJECTED) {
fxaLoginStatus.selectedIndex = FXA_LOGIN_FAILED;
syncReady = false;
// Else we must be golden (or in an error state we expect to magically
// resolve itself)
} else {
fxaLoginStatus.selectedIndex = FXA_LOGIN_VERIFIED;
syncReady = true;
}
fxaEmailAddress1Label.textContent = data.email;
document.getElementById("fxaEmailAddress2").textContent = data.email;
document.getElementById("fxaEmailAddress3").textContent = data.email;
this._populateComputerName(Weave.Service.clientsEngine.localName);
let engines = document.getElementById("fxaSyncEngines")
for (let checkbox of engines.querySelectorAll("checkbox")) {
checkbox.disabled = !syncReady;
}
document.getElementById("fxaChangeDeviceName").disabled = !syncReady;
// Clear the profile image (if any) of the previously logged in account.
document.getElementById("fxaProfileImage").style.removeProperty("list-style-image");
// Clear the profile image (if any) of the previously logged in account.
document.getElementById("fxaProfileImage").style.removeProperty("list-style-image");
// If the account is verified the next promise in the chain will
// fetch profile data.
return data.verified;
}).then(isVerified => {
if (isVerified) {
return fxAccounts.getSignedInUserProfile();
}
return null;
}).then(data => {
let fxaLoginStatus = document.getElementById("fxaLoginStatus");
if (data && profileInfoEnabled) {
if (data.displayName) {
fxaLoginStatus.setAttribute("hasName", true);
displayNameLabel.hidden = false;
displayNameLabel.textContent = data.displayName;
} else {
fxaLoginStatus.removeAttribute("hasName");
}
if (data.avatar) {
let bgImage = "url(\"" + data.avatar + "\")";
let profileImageElement = document.getElementById("fxaProfileImage");
profileImageElement.style.listStyleImage = bgImage;
// If the account is verified the next promise in the chain will
// fetch profile data.
return data.verified;
}).then(isVerified => {
if (isVerified) {
return fxAccounts.getSignedInUserProfile();
}
return null;
}).then(data => {
let fxaLoginStatus = document.getElementById("fxaLoginStatus");
if (data && profileInfoEnabled) {
if (data.displayName) {
fxaLoginStatus.setAttribute("hasName", true);
displayNameLabel.hidden = false;
displayNameLabel.textContent = data.displayName;
let img = new Image();
img.onerror = () => {
// Clear the image if it has trouble loading. Since this callback is asynchronous
// we check to make sure the image is still the same before we clear it.
if (profileImageElement.style.listStyleImage === bgImage) {
profileImageElement.style.removeProperty("list-style-image");
}
};
img.src = data.avatar;
}
} else {
fxaLoginStatus.removeAttribute("hasName");
}
if (data.avatar) {
let bgImage = "url(\"" + data.avatar + "\")";
let profileImageElement = document.getElementById("fxaProfileImage");
profileImageElement.style.listStyleImage = bgImage;
}, err => {
FxAccountsCommon.log.error(err);
}).catch(err => {
// If we get here something's really busted
Cu.reportError(String(err));
});
let img = new Image();
img.onerror = () => {
// Clear the image if it has trouble loading. Since this callback is asynchronous
// we check to make sure the image is still the same before we clear it.
if (profileImageElement.style.listStyleImage === bgImage) {
profileImageElement.style.removeProperty("list-style-image");
}
};
img.src = data.avatar;
}
} else {
fxaLoginStatus.removeAttribute("hasName");
}
}, err => {
FxAccountsCommon.log.error(err);
}).catch(err => {
// If we get here something's really busted
Cu.reportError(String(err));
});
// If fxAccountEnabled is false and we are in a "not configured" state,
// then fxAccounts is probably fully disabled rather than just unconfigured,
// so handle this case. This block can be removed once we remove support
// for fxAccounts being disabled.
} else if (Weave.Status.service == Weave.CLIENT_NOT_CONFIGURED ||
Weave.Svc.Prefs.get("firstSync", "") == "notReady") {
this.page = PAGE_NO_ACCOUNT;
// else: sync was previously configured for the legacy provider, so we
// make the "old" panels available.
} else if (Weave.Status.login == Weave.LOGIN_FAILED_INVALID_PASSPHRASE ||
Weave.Status.login == Weave.LOGIN_FAILED_LOGIN_REJECTED) {
this.needsUpdate();
} else {
this.page = PAGE_HAS_ACCOUNT;
document.getElementById("accountName").textContent = Weave.Service.identity.account;
document.getElementById("syncComputerName").value = Weave.Service.clientsEngine.localName;
document.getElementById("tosPP-normal").hidden = this._usingCustomServer;
}
},
startOver(showDialog) {
if (showDialog) {
let flags = Services.prompt.BUTTON_POS_0 * Services.prompt.BUTTON_TITLE_IS_STRING +
Services.prompt.BUTTON_POS_1 * Services.prompt.BUTTON_TITLE_CANCEL +
Services.prompt.BUTTON_POS_1_DEFAULT;
let buttonChoice =
Services.prompt.confirmEx(window,
this._stringBundle.GetStringFromName("syncUnlink.title"),
this._stringBundle.GetStringFromName("syncUnlink.label"),
flags,
this._stringBundle.GetStringFromName("syncUnlinkConfirm.label"),
null, null, null, {});
// If the user selects cancel, just bail
if (buttonChoice == 1)
return;
}
Weave.Service.startOver();
this.updateWeavePrefs();
},
updatePass() {
if (Weave.Status.login == Weave.LOGIN_FAILED_LOGIN_REJECTED)
gSyncUtils.changePassword();
else
gSyncUtils.updatePassphrase();
},
resetPass() {
if (Weave.Status.login == Weave.LOGIN_FAILED_LOGIN_REJECTED)
gSyncUtils.resetPassword();
else
gSyncUtils.resetPassphrase();
},
_getEntryPoint() {
@ -359,10 +477,41 @@ var gSyncPane = {
this.replaceTabWithUrl("about:accounts?" + params);
},
/**
* Invoke the Sync setup wizard.
*
* @param wizardType
* Indicates type of wizard to launch:
* null -- regular set up wizard
* "pair" -- pair a device first
* "reset" -- reset sync
*/
openSetup(wizardType) {
let service = Components.classes["@mozilla.org/weave/service;1"]
.getService(Components.interfaces.nsISupports)
.wrappedJSObject;
if (service.fxAccountsEnabled) {
this._openAboutAccounts();
} else {
let win = Services.wm.getMostRecentWindow("Weave:AccountSetup");
if (win)
win.focus();
else {
window.openDialog("chrome://browser/content/sync/setup.xul",
"weaveSetup", "centerscreen,chrome,resizable=no",
wizardType);
}
}
},
openContentInBrowser(url, options) {
let win = Services.wm.getMostRecentWindow("navigator:browser");
if (!win) {
openUILinkIn(url, "tab");
// no window to use, so use _openLink to create a new one. We don't
// always use that as it prefers to open a new window rather than use
// an existing one.
gSyncUtils._openLink(url);
return;
}
win.switchToTabHavingURI(url, true, options);
@ -458,6 +607,11 @@ var gSyncPane = {
.then(onSuccess, onError);
},
openOldSyncSupportPage() {
let url = Services.urlFormatter.formatURLPref("app.support.baseURL") + "old-sync";
this.openContentInBrowser(url);
},
unlinkFirefoxAccount(confirm) {
if (confirm) {
// We use a string bundle shared with aboutAccounts.
@ -490,6 +644,22 @@ var gSyncPane = {
});
},
openAddDevice() {
if (!Weave.Utils.ensureMPUnlocked())
return;
let win = Services.wm.getMostRecentWindow("Sync:AddDevice");
if (win)
win.focus();
else
window.openDialog("chrome://browser/content/sync/addDevice.xul",
"syncAddDevice", "centerscreen,chrome,resizable=no");
},
resetSync() {
this.openSetup("reset");
},
_populateComputerName(value) {
let textbox = document.getElementById("fxaSyncComputerName");
if (!textbox.hasAttribute("placeholder")) {

View File

@ -27,6 +27,8 @@
<script type="application/javascript"
src="chrome://browser/content/preferences/in-content/sync.js"/>
<script type="application/javascript"
src="chrome://browser/content/sync/utils.js"/>
<hbox id="header-sync"
class="header"
@ -37,6 +39,138 @@
</hbox>
<deck id="weavePrefsDeck" data-category="paneSync" hidden="true">
<!-- These panels are for the "legacy" sync provider -->
<vbox id="noAccount" align="center">
<spacer flex="1"/>
<description id="syncDesc">
&weaveDesc.label;
</description>
<separator/>
<label id="noAccountSetup" class="text-link">
&setupButton.label;
</label>
<vbox id="pairDevice">
<separator/>
<label id="noAccountPair" class="text-link">
&pairDevice.label;
</label>
</vbox>
<spacer flex="3"/>
</vbox>
<vbox id="hasAccount">
<groupbox class="syncGroupBox">
<!-- label is set to account name -->
<caption id="accountCaption" align="center">
<image id="accountCaptionImage"/>
<label id="accountName"/>
</caption>
<hbox>
<button type="menu"
label="&manageAccount.label;"
accesskey="&manageAccount.accesskey;">
<menupopup>
<menuitem id="syncChangePassword" label="&changePassword2.label;"/>
<menuitem id="syncResetPassphrase" label="&myRecoveryKey.label;"/>
<menuseparator/>
<menuitem id="syncReset" label="&resetSync2.label;"/>
</menupopup>
</button>
</hbox>
<hbox>
<label id="syncAddDeviceLabel"
class="text-link">
&pairDevice.label;
</label>
</hbox>
<vbox>
<label>&syncMy.label;</label>
<richlistbox id="syncEnginesList"
orient="vertical">
<richlistitem>
<checkbox label="&engine.addons.label;"
accesskey="&engine.addons.accesskey;"
preference="engine.addons"/>
</richlistitem>
<richlistitem>
<checkbox label="&engine.bookmarks.label;"
accesskey="&engine.bookmarks.accesskey;"
preference="engine.bookmarks"/>
</richlistitem>
<richlistitem>
<checkbox label="&engine.passwords.label;"
accesskey="&engine.passwords.accesskey;"
preference="engine.passwords"/>
</richlistitem>
<richlistitem>
<checkbox label="&engine.prefs.label;"
accesskey="&engine.prefs.accesskey;"
preference="engine.prefs"/>
</richlistitem>
<richlistitem>
<checkbox label="&engine.history.label;"
accesskey="&engine.history.accesskey;"
preference="engine.history"/>
</richlistitem>
<richlistitem>
<checkbox label="&engine.tabs.label2;"
accesskey="&engine.tabs.accesskey;"
preference="engine.tabs"/>
</richlistitem>
</richlistbox>
</vbox>
</groupbox>
<groupbox class="syncGroupBox">
<grid>
<columns>
<column/>
<column flex="1"/>
</columns>
<rows>
<row align="center">
<label control="syncComputerName">
&syncDeviceName.label;
</label>
<textbox id="syncComputerName"/>
</row>
</rows>
</grid>
<hbox>
<label id="unlinkDevice" class="text-link">
&unlinkDevice.label;
</label>
</hbox>
</groupbox>
<vbox id="tosPP-normal">
<label id="tosPP-normal-ToS" class="text-link">
&prefs.tosLink.label;
</label>
<label id="tosPP-normal-PP" class="text-link">
&prefs.ppLink.label;
</label>
</vbox>
</vbox>
<vbox id="needsUpdate" align="center" pack="center">
<hbox>
<label id="loginError"/>
<label id="loginErrorUpdatePass" class="text-link">
&updatePass.label;
</label>
<label id="loginErrorResetPass" class="text-link">
&resetPass.label;
</label>
</hbox>
<label id="loginErrorStartOver" class="text-link">
&unlinkDevice.label;
</label>
</vbox>
<!-- These panels are for the Firefox Accounts identity provider -->
<vbox id="noFxaAccount">
<hbox>
<vbox id="fxaContentWrapper">

View File

@ -166,7 +166,7 @@ SyncedTabsDeckComponent.prototype = {
},
openSyncPrefs() {
this._getChromeWindow(this._window).gSyncUI.openPrefs("tabs-sidebar");
this._getChromeWindow(this._window).gSyncUI.openSetup(null, "tabs-sidebar");
}
};

View File

@ -212,11 +212,11 @@ add_task(function* testActions() {
};
let chromeWindowMock = {
gSyncUI: {
openPrefs() {}
openSetup() {}
}
};
sinon.spy(windowMock, "openUILink");
sinon.spy(chromeWindowMock.gSyncUI, "openPrefs");
sinon.spy(chromeWindowMock.gSyncUI, "openSetup");
let getChromeWindowMock = sinon.stub();
getChromeWindowMock.returns(chromeWindowMock);
@ -236,5 +236,5 @@ add_task(function* testActions() {
component.openSyncPrefs();
Assert.ok(getChromeWindowMock.calledWith(windowMock));
Assert.ok(chromeWindowMock.gSyncUI.openPrefs.called);
Assert.ok(chromeWindowMock.gSyncUI.openSetup.called);
});

View File

@ -8,7 +8,7 @@ support-files =
[browser_backgroundTab.js]
[browser_closeTab.js]
[browser_fxa.js]
skip-if = debug || asan # updateUI leaks
skip-if = debug || asan # updateAppMenuItem leaks
[browser_no_tabs.js]
[browser_openPreferences.js]
[browser_openSearchPanel.js]

View File

@ -18,7 +18,7 @@ function test() {
registerCleanupFunction(function*() {
yield signOut();
gFxAccounts.updateUI();
gFxAccounts.updateAppMenuItem();
});
var tests = [
@ -35,7 +35,7 @@ var tests = [
yield setSignedInUser();
let userData = yield fxAccounts.getSignedInUser();
isnot(userData, null, "Logged in now");
gFxAccounts.updateUI(); // Causes a leak (see bug 1332985)
gFxAccounts.updateAppMenuItem(); // Causes a leak
yield showMenuPromise("appMenu");
yield showHighlightPromise("accountStatus");
let highlight = document.getElementById("UITourHighlightContainer");

View File

@ -299,6 +299,7 @@
@RESPATH@/components/satchel.xpt
@RESPATH@/components/saxparser.xpt
@RESPATH@/browser/components/sessionstore.xpt
@RESPATH@/components/services-crypto-component.xpt
@RESPATH@/components/captivedetect.xpt
@RESPATH@/browser/components/shellservice.xpt
@RESPATH@/components/shistory.xpt

View File

@ -6,6 +6,7 @@
<!ENTITY aboutAccountsConfig.description "Sign in to sync your tabs, bookmarks, passwords &amp; more.">
<!ENTITY aboutAccountsConfig.startButton.label "Get started">
<!ENTITY aboutAccountsConfig.useOldSync.label "Using an older version of Sync?">
<!ENTITY aboutAccountsConfig.syncPreferences.label "Sync preferences">
<!ENTITY aboutAccounts.noConnection.title "No connection">
<!ENTITY aboutAccounts.noConnection.description "You must be connected to the Internet to sign in.">

View File

@ -2,6 +2,14 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# autoDisconnectDescription is shown in an info bar when we detect an old
# Sync is being used.
autoDisconnectDescription = Weve rebuilt Sync to make it easier for everyone.
# autoDisconnectSignIn.label and .accessKey are for buttons when we auto-disconnect
autoDisconnectSignIn.label = Sign in to Sync
autoDisconnectSignIn.accessKey = S
# LOCALIZATION NOTE (reconnectDescription) - %S = Email address of user's Firefox Account
reconnectDescription = Reconnect %S

View File

@ -177,6 +177,10 @@ important=Important
default=Default
siteUsage=%1$S %2$S
syncUnlink.title=Do you want to unlink your device?
syncUnlink.label=This device will no longer be associated with your Sync account. All of your personal data, both on this device and in your Sync account, will remain intact.
syncUnlinkConfirm.label=Unlink
# LOCALIZATION NOTE (featureEnableRequiresRestart, featureDisableRequiresRestart, restartTitle): %S = brandShortName
featureEnableRequiresRestart=%S must restart to enable this feature.
featureDisableRequiresRestart=%S must restart to disable this feature.

View File

@ -2,8 +2,27 @@
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<!-- The page shown when not logged in... -->
<!ENTITY setupButton.label "Set Up &syncBrand.fullName.label;">
<!ENTITY setupButton.accesskey "S">
<!ENTITY weaveDesc.label "&syncBrand.fullName.label; lets you access your history, bookmarks, passwords and open tabs across all your devices.">
<!-- The page shown when logged in... -->
<!-- Login error feedback -->
<!ENTITY updatePass.label "Update">
<!ENTITY resetPass.label "Reset">
<!-- Manage Account -->
<!ENTITY manageAccount.label "Manage Account">
<!ENTITY manageAccount.accesskey "n">
<!ENTITY changePassword2.label "Change Password…">
<!ENTITY myRecoveryKey.label "My Recovery Key">
<!ENTITY resetSync2.label "Reset Sync…">
<!ENTITY pairDevice.label "Pair a Device">
<!ENTITY syncMy.label "Sync My">
<!ENTITY engine.bookmarks.label "Bookmarks">
<!ENTITY engine.bookmarks.accesskey "m">
<!ENTITY engine.tabs.label2 "Open Tabs">
@ -18,6 +37,7 @@
<!ENTITY engine.addons.accesskey "A">
<!-- Device Settings -->
<!ENTITY syncDeviceName.label "Device Name:">
<!ENTITY fxaSyncDeviceName.label "Device Name">
<!ENTITY changeSyncDeviceName.label "Change Device Name…">
<!ENTITY changeSyncDeviceName.accesskey "h">
@ -25,10 +45,15 @@
<!ENTITY cancelChangeSyncDeviceName.accesskey "n">
<!ENTITY saveChangeSyncDeviceName.label "Save">
<!ENTITY saveChangeSyncDeviceName.accesskey "v">
<!ENTITY unlinkDevice.label "Unlink This Device">
<!-- Footer stuff -->
<!ENTITY prefs.tosLink.label "Terms of Service">
<!ENTITY prefs.ppLink.label "Privacy Policy">
<!-- Firefox Accounts stuff -->
<!ENTITY fxaPrivacyNotice.link.label "Privacy Notice">
<!ENTITY determiningAcctStatus.label "Determining your account status…">
<!-- LOCALIZATION NOTE (signedInUnverified.beforename.label,
signedInUnverified.aftername.label): these two string are used respectively
@ -59,6 +84,12 @@ both, to better adapt this sentence to their language.
<!ENTITY forget.label "Forget this Email">
<!ENTITY forget.accesskey "F">
<!ENTITY welcome.description "Access your tabs, bookmarks, passwords and more wherever you use &brandShortName;.">
<!ENTITY welcome.signIn.label "Sign In">
<!ENTITY welcome.createAccount.label "Create Account">
<!ENTITY welcome.useOldSync.label "Using an older version of Sync?">
<!ENTITY signedOut.caption "Take your Web with you">
<!ENTITY signedOut.description "Synchronize your bookmarks, history, tabs, passwords, add-ons, and preferences across all your devices.">
<!ENTITY signedOut.accountBox.title "Connect with a &syncBrand.fxAccount.label;">

View File

@ -0,0 +1,27 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<!ENTITY syncCustomize.dialog.title "Sync Selection">
<!ENTITY syncCustomize.acceptButton.label "Start">
<!ENTITY syncCustomize.title "What would you like to sync?">
<!ENTITY syncCustomize.description "You can change this selection in Options.">
<!ENTITY syncCustomizeUnix.description "You can change this selection in Preferences.">
<!--
These engine names are the same as in browser/preferences/sync.dtd except
for the last two that are marked as being specific to Desktop browsers.
-->
<!ENTITY engine.bookmarks.label "Bookmarks">
<!ENTITY engine.bookmarks.accesskey "m">
<!ENTITY engine.history.label "History">
<!ENTITY engine.history.accesskey "r">
<!ENTITY engine.tabs.label2 "Open Tabs">
<!ENTITY engine.tabs.accesskey "T">
<!ENTITY engine.passwords.label "Passwords">
<!ENTITY engine.passwords.accesskey "P">
<!ENTITY engine.addons.label "Desktop Add-ons">
<!ENTITY engine.addons.accesskey "A">
<!ENTITY engine.prefs.label "Desktop Preferences">
<!ENTITY engine.prefs.accesskey "S">

View File

@ -0,0 +1,37 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#LOCALIZATION NOTE (change.password.title): This (and associated change.password/passphrase) are used when the user elects to change their password.
change.password.title = Change your Password
change.password.acceptButton = Change Password
change.password.status.active = Changing your password…
change.password.status.success = Your password has been changed.
change.password.status.error = There was an error changing your password.
change.password3.introText = Your password must be at least 8 characters long. It cannot be the same as either your user name or your Recovery Key.
change.password.warningText = Note: All of your other devices will be unable to connect to your account once you change this password.
change.recoverykey.title = My Recovery Key
change.recoverykey.acceptButton = Change Recovery Key
change.recoverykey.label = Changing Recovery Key and uploading local data, please wait…
change.recoverykey.error = There was an error while changing your Recovery Key!
change.recoverykey.success = Your Recovery Key was successfully changed!
change.synckey.introText2 = To ensure your total privacy, all of your data is encrypted prior to being uploaded. The key to decrypt your data is not uploaded.
# LOCALIZATION NOTE (change.recoverykey.warningText) "Sync" should match &syncBrand.shortName.label; from syncBrand.dtd
change.recoverykey.warningText = Note: Changing this will erase all data stored on the Sync server and upload new data secured by this Recovery Key. Your other devices will not sync until the new Recovery Key is entered for that device.
new.recoverykey.label = Your Recovery Key
# LOCALIZATION NOTE (new.password.title): This (and associated new.password/passphrase) are used on a second computer when it detects that your password or passphrase has been changed on a different device.
new.password.title = Update Password
new.password.introText = Your password was rejected by the server, please update your password.
new.password.label = Enter your new password
new.password.confirm = Confirm your new password
new.password.acceptButton = Update Password
new.password.status.incorrect = Password incorrect, please try again.
new.recoverykey.title = Update Recovery Key
new.recoverykey.introText = Your Recovery Key was changed using another device, please enter your updated Recovery Key.
new.recoverykey.acceptButton = Update Recovery Key

View File

@ -0,0 +1,18 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<!ENTITY syncKey.page.title "Your &syncBrand.fullName.label; Key">
<!ENTITY syncKey.page.description2 "This key is used to decode the data in your &syncBrand.fullName.label; account. You will need to enter the key each time you configure &syncBrand.fullName.label; on a new device.">
<!ENTITY syncKey.keepItSecret.heading "Keep it secret">
<!ENTITY syncKey.keepItSecret.description "Your &syncBrand.fullName.label; account is encrypted to protect your privacy. Without this key, it would take years for anyone to decode your personal information. You are the only person who holds this key. This means youre the only one who can access your &syncBrand.fullName.label; data.">
<!ENTITY syncKey.keepItSafe.heading "Keep it safe">
<!ENTITY syncKey.keepItSafe1.description "Do not lose this key.">
<!ENTITY syncKey.keepItSafe2.description " We dont keep a copy of your key (that wouldnt be keeping it secret!) so ">
<!ENTITY syncKey.keepItSafe3.description "we cant help you recover it">
<!ENTITY syncKey.keepItSafe4a.description " if its lost. Youll need to use this key any time you connect a new device to &syncBrand.fullName.label;.">
<!ENTITY syncKey.findOutMore1.label "Find out more about &syncBrand.fullName.label; and your privacy at ">
<!ENTITY syncKey.findOutMore2.label ".">
<!ENTITY syncKey.footer1.label "&syncBrand.fullName.label; Terms of Service are available at ">
<!ENTITY syncKey.footer2.label ". The Privacy Policy is available at ">
<!ENTITY syncKey.footer3.label ".">

View File

@ -0,0 +1,8 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<!ENTITY quota.dialogTitle.label "Server Quota">
<!ENTITY quota.retrievingInfo.label "Retrieving quota information…">
<!ENTITY quota.typeColumn.label "Type">
<!ENTITY quota.sizeColumn.label "Size">

View File

@ -0,0 +1,42 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
collection.addons.label = Add-ons
collection.bookmarks.label = Bookmarks
collection.history.label = History
collection.passwords.label = Passwords
collection.prefs.label = Preferences
collection.tabs.label = Tabs
# LOCALIZATION NOTE (quota.usageNoQuota.label): %1$S and %2$S are numeric value
# and unit (as defined in the download manager) of the amount of space occupied
# on the server
quota.usageNoQuota.label = You are currently using %1$S %2$S.
# LOCALIZATION NOTE (quota.usagePercentage.label):
# %1$S is the percentage of space used,
# %2$S and %3$S numeric value and unit (as defined in the download manager)
# of the amount of space used,
# %3$S and %4$S numeric value and unit (as defined in the download manager)
# of the total space available.
quota.usagePercentage.label = You are using %1$S%% (%2$S %3$S) of your allowed %4$S %5$S.
quota.usageError.label = Could not retrieve quota information.
quota.retrieving.label = Retrieving…
# LOCALIZATION NOTE (quota.sizeValueUnit.label): %1$S is the amount of space
# occupied by the engine, %2$K the corresponding unit (e.g. kB) as defined in
# the download manager.
quota.sizeValueUnit.label = %1$S %2$S
quota.remove.label = Remove
quota.treeCaption.label = Uncheck items to stop syncing them and free up space on the server.
# LOCALIZATION NOTE (quota.removal.label): %S is a list of engines that will be
# disabled and whose data will be removed once the user confirms.
quota.removal.label = Firefox Sync will remove the following data: %S.
# LOCALIZATION NOTE (quota.list.separator): This is the separator string used
# for the list of engines (incl. spaces where appropriate)
quota.list.separator = ,\u0020
# LOCALIZATION NOTE (quota.freeup.label): %1$S and %2$S are numeric value
# and unit (as defined in the download manager) of the amount of space freed
# up by disabling the unchecked engines. If displayed this string is
# concatenated directly to quota.removal.label and may need to start off with
# whitespace.
quota.freeup.label = \u0020This will free up %1$S %2$S.

View File

@ -0,0 +1,114 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<!ENTITY accountSetupTitle.label "&syncBrand.fullName.label; Setup">
<!-- First page of the wizard -->
<!ENTITY setup.pickSetupType.description2 "Welcome! If youve never used &syncBrand.fullName.label; before, you will need to create a new account.">
<!ENTITY button.createNewAccount.label "Create a New Account">
<!ENTITY button.haveAccount.label "I Have an Account">
<!ENTITY setup.choicePage.title.label "Have you used &syncBrand.fullName.label; before?">
<!ENTITY setup.choicePage.new.label "Ive never used &syncBrand.shortName.label; before">
<!ENTITY setup.choicePage.existing2.label "Im already using &syncBrand.shortName.label; on another device">
<!-- New Account AND Existing Account -->
<!ENTITY server.label "Server">
<!ENTITY serverType.default.label "Default: Mozilla &syncBrand.fullName.label; server">
<!ENTITY serverType.custom2.label "Use a custom server…">
<!ENTITY signIn.account2.label "Account">
<!ENTITY signIn.account2.accesskey "A">
<!ENTITY signIn.password.label "Password">
<!ENTITY signIn.password.accesskey "P">
<!ENTITY signIn.recoveryKey.label "Recovery Key">
<!ENTITY signIn.recoveryKey.accesskey "K">
<!-- New Account Page 1: Basic Account Info -->
<!ENTITY setup.newAccountDetailsPage.title.label "Account Details">
<!ENTITY setup.emailAddress.label "Email Address">
<!ENTITY setup.emailAddress.accesskey "E">
<!ENTITY setup.choosePassword.label "Choose a Password">
<!ENTITY setup.choosePassword.accesskey "P">
<!ENTITY setup.confirmPassword.label "Confirm Password">
<!ENTITY setup.confirmPassword.accesskey "m">
<!-- LOCALIZATION NOTE: tosAgree1, tosLink, tosAgree2, ppLink, tosAgree3 are
joined with implicit white space, so spaces in the strings aren't necessary -->
<!ENTITY setup.tosAgree1.label "I agree to the">
<!ENTITY setup.tosAgree1.accesskey "a">
<!ENTITY setup.tosLink.label "Terms of Service">
<!ENTITY setup.tosAgree2.label "and the">
<!ENTITY setup.ppLink.label "Privacy Policy">
<!ENTITY setup.tosAgree3.label "">
<!ENTITY setup.tosAgree2.accesskey "">
<!-- My Recovery Key dialog -->
<!ENTITY setup.newRecoveryKeyPage.title.label "&brandShortName; Cares About Your Privacy">
<!ENTITY setup.newRecoveryKeyPage.description.label "To ensure your total privacy, all of your data is encrypted prior to being uploaded. The Recovery Key which is necessary to decrypt your data is not uploaded.">
<!ENTITY recoveryKeyEntry.label "Your Recovery Key">
<!ENTITY recoveryKeyEntry.accesskey "K">
<!ENTITY syncGenerateNewKey.label "Generate a new key">
<!ENTITY recoveryKeyBackup.description "Your Recovery Key is required to access &syncBrand.fullName.label; on other machines. Please create a backup copy. We cannot help you recover your Recovery Key.">
<!ENTITY button.syncKeyBackup.print.label "Print…">
<!ENTITY button.syncKeyBackup.print.accesskey "P">
<!ENTITY button.syncKeyBackup.save.label "Save…">
<!ENTITY button.syncKeyBackup.save.accesskey "S">
<!-- Existing Account Page 1: Pair a Device (incl. Pair a Device dialog strings) -->
<!ENTITY pairDevice.title.label "Pair a Device">
<!ENTITY addDevice.showMeHow.label "Show me how.">
<!ENTITY addDevice.dontHaveDevice.label "I dont have the device with me">
<!ENTITY pairDevice.setup.description.label "To activate, select &#x0022;Pair a Device&#x0022; on your other device.">
<!ENTITY addDevice.setup.enterCode.label "Then, enter this code:">
<!ENTITY pairDevice.dialog.description.label "To activate your new device, select &#x0022;Set Up Sync&#x0022; on the device.">
<!ENTITY addDevice.dialog.enterCode.label "Enter the code that the device provides:">
<!ENTITY addDevice.dialog.tryAgain.label "Please try again.">
<!ENTITY addDevice.dialog.successful.label "The device has been successfully added. The initial synchronization can take several minutes and will finish in the background.">
<!ENTITY addDevice.dialog.recoveryKey.label "To activate your device you will need to enter your Recovery Key. Please print or save this key and take it with you.">
<!ENTITY addDevice.dialog.connected.label "Device Connected">
<!-- Existing Account Page 2: Manual Login -->
<!ENTITY setup.signInPage.title.label "Sign In">
<!ENTITY existingRecoveryKey.description "You can get a copy of your Recovery Key by going to &syncBrand.shortName.label; Options on your other device, and selecting &#x0022;My Recovery Key&#x0022; under &#x0022;Manage Account&#x0022;.">
<!ENTITY verifying.label "Verifying…">
<!ENTITY resetPassword.label "Reset Password">
<!ENTITY resetSyncKey.label "I have lost my other device.">
<!-- Sync Options -->
<!ENTITY setup.optionsPage.title "Sync Options">
<!ENTITY syncDeviceName.label "Device Name:">
<!ENTITY syncDeviceName.accesskey "c">
<!ENTITY syncMy.label "Sync My">
<!ENTITY engine.bookmarks.label "Bookmarks">
<!ENTITY engine.bookmarks.accesskey "m">
<!ENTITY engine.tabs.label2 "Open Tabs">
<!ENTITY engine.tabs.accesskey "T">
<!ENTITY engine.history.label "History">
<!ENTITY engine.history.accesskey "r">
<!ENTITY engine.passwords.label "Passwords">
<!ENTITY engine.passwords.accesskey "P">
<!ENTITY engine.prefs.label "Preferences">
<!ENTITY engine.prefs.accesskey "S">
<!ENTITY engine.addons.label "Add-ons">
<!ENTITY engine.addons.accesskey "A">
<!ENTITY choice2a.merge.main.label "Merge this devices data with my &syncBrand.shortName.label; data">
<!ENTITY choice2.merge.recommended.label "Recommended:">
<!ENTITY choice2a.client.main.label "Replace all data on this device with my &syncBrand.shortName.label; data">
<!ENTITY choice2a.server.main.label "Replace all other devices with this devices data">
<!-- Confirm Merge Options -->
<!ENTITY setup.optionsConfirmPage.title "Confirm">
<!ENTITY confirm.merge2.label "&syncBrand.fullName.label; will now merge all this devices browser data into your Sync account.">
<!ENTITY confirm.client3.label "Warning: The following &brandShortName; data on this device will be deleted:">
<!ENTITY confirm.client2.moreinfo.label "&brandShortName; will then copy your &syncBrand.fullName.label; data to this device.">
<!ENTITY confirm.server2.label "Warning: The following devices will be overwritten with your local data:">
<!-- New & Existing Account: Setup Complete -->
<!ENTITY setup.successPage.title "Setup Complete">
<!ENTITY changeOptions.label "You can change this preference by selecting Sync Options below.">
<!ENTITY continueUsing.label "You may now continue using &brandShortName;.">

View File

@ -2,6 +2,51 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
button.syncOptions.label = Sync Options
button.syncOptionsDone.label = Done
button.syncOptionsCancel.label = Cancel
invalidEmail.label = Invalid email address
serverInvalid.label = Please enter a valid server URL
usernameNotAvailable.label = Already in use
verifying.label = Verifying…
# LOCALIZATION NOTE (additionalClientCount.label):
# Semicolon-separated list of plural forms. See:
# http://developer.mozilla.org/en/docs/Localization_and_Plurals
# #1 is the number of additional clients (was %S for a short while, use #1 instead, even if both work)
additionalClientCount.label = and #1 additional device;and #1 additional devices
# LOCALIZATION NOTE (bookmarksCount.label):
# Semicolon-separated list of plural forms. See:
# http://developer.mozilla.org/en/docs/Localization_and_Plurals
# #1 is the number of bookmarks (was %S for a short while, use #1 instead, even if both work)
bookmarksCount.label = #1 bookmark;#1 bookmarks
# LOCALIZATION NOTE (historyDaysCount.label):
# Semicolon-separated list of plural forms. See:
# http://developer.mozilla.org/en/docs/Localization_and_Plurals
# #1 is the number of days (was %S for a short while, use #1 instead, even if both work)
historyDaysCount.label = #1 day of history;#1 days of history
# LOCALIZATION NOTE (passwordsCount.label):
# Semicolon-separated list of plural forms. See:
# http://developer.mozilla.org/en/docs/Localization_and_Plurals
# #1 is the number of passwords (was %S for a short while, use #1 instead, even if both work)
passwordsCount.label = #1 password;#1 passwords
# LOCALIZATION NOTE (addonsCount.label): Semicolon-separated list of plural forms.
# See: http://developer.mozilla.org/en/docs/Localization_and_Plurals
# #1 is the number of add-ons, see the link above for forms
addonsCount.label = #1 add-on;#1 add-ons
save.recoverykey.title = Save Recovery Key
save.recoverykey.defaultfilename = Firefox Recovery Key.html
newAccount.action.label = Firefox Sync is now set up to automatically sync all of your browser data.
newAccount.change.label = You can choose exactly what to sync by selecting Sync Options below.
resetClient.change2.label = Firefox Sync will now merge all this devices browser data into your Sync account.
wipeClient.change2.label = Firefox Sync will now replace all of the browser data on this device with the data in your Sync account.
wipeRemote.change2.label = Firefox Sync will now replace all of the browser data in your Sync account with the data on this device.
existingAccount.change.label = You can change this preference by selecting Sync Options below.
# Several other strings are used (via Weave.Status.login), but they come from
# /services/sync

View File

@ -20,6 +20,7 @@
locale/browser/aboutSearchReset.dtd (%chrome/browser/aboutSearchReset.dtd)
locale/browser/aboutSessionRestore.dtd (%chrome/browser/aboutSessionRestore.dtd)
locale/browser/aboutTabCrashed.dtd (%chrome/browser/aboutTabCrashed.dtd)
locale/browser/syncCustomize.dtd (%chrome/browser/syncCustomize.dtd)
locale/browser/aboutSyncTabs.dtd (%chrome/browser/aboutSyncTabs.dtd)
locale/browser/browser.dtd (%chrome/browser/browser.dtd)
locale/browser/baseMenuOverlay.dtd (%chrome/browser/baseMenuOverlay.dtd)
@ -84,7 +85,12 @@
locale/browser/preferences/siteDataSettings.dtd (%chrome/browser/preferences/siteDataSettings.dtd)
locale/browser/preferences/translation.dtd (%chrome/browser/preferences/translation.dtd)
locale/browser/syncBrand.dtd (%chrome/browser/syncBrand.dtd)
locale/browser/syncSetup.dtd (%chrome/browser/syncSetup.dtd)
locale/browser/syncSetup.properties (%chrome/browser/syncSetup.properties)
locale/browser/syncGenericChange.properties (%chrome/browser/syncGenericChange.properties)
locale/browser/syncKey.dtd (%chrome/browser/syncKey.dtd)
locale/browser/syncQuota.dtd (%chrome/browser/syncQuota.dtd)
locale/browser/syncQuota.properties (%chrome/browser/syncQuota.properties)
% resource search-plugins chrome://browser/locale/searchplugins/
#if BUILD_FASTER
locale/browser/searchplugins/ (searchplugins/*.xml)

View File

@ -114,6 +114,9 @@ browser.jar:
skin/classic/browser/sync-horizontalbar@2x.png
skin/classic/browser/sync-mobileIcon.svg (../shared/sync-mobileIcon.svg)
skin/classic/browser/sync-notification-24.png
skin/classic/browser/syncSetup.css
skin/classic/browser/syncCommon.css
skin/classic/browser/syncQuota.css
skin/classic/browser/syncProgress-horizontalbar.png
skin/classic/browser/syncProgress-horizontalbar@2x.png
#ifdef E10S_TESTING_ONLY

View File

@ -83,6 +83,19 @@
/* Sync Pane */
#syncDesc {
padding: 0 8em;
}
#accountCaptionImage {
list-style-image: url("chrome://mozapps/skin/profile/profileicon.png");
}
#syncAddDeviceLabel {
margin-top: 1em;
margin-bottom: 1em;
}
#noFxaAccount {
line-height: 1.2em;
}

View File

@ -0,0 +1,49 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* The following are used by both sync/setup.xul and sync/genericChange.xul */
.status {
color: -moz-dialogtext;
}
.statusIcon {
margin-inline-start: 4px;
max-height: 16px;
max-width: 16px;
}
.statusIcon[status="active"] {
list-style-image: url("chrome://global/skin/icons/loading.png");
}
.statusIcon[status="error"] {
list-style-image: url("moz-icon://stock/gtk-dialog-error?size=menu");
}
.statusIcon[status="success"] {
list-style-image: url("moz-icon://stock/gtk-dialog-info?size=menu");
}
/* .data is only used by sync/genericChange.xul, but it seems unnecessary to have
a separate stylesheet for it. */
.data {
font-size: 90%;
font-weight: bold;
}
dialog#change-dialog {
width: 40em;
}
image#syncIcon {
list-style-image: url("chrome://browser/skin/sync-32.png");
}
#introText {
margin-top: 2px;
}
#feedback {
height: 2em;
}

View File

@ -0,0 +1,26 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#quotaDialog {
width: 33em;
height: 25em;
}
treechildren::-moz-tree-checkbox {
list-style-image: none;
}
treechildren::-moz-tree-checkbox(checked) {
list-style-image: url("chrome://global/skin/checkbox/cbox-check.gif");
}
treechildren::-moz-tree-checkbox(disabled) {
list-style-image: url("chrome://global/skin/checkbox/cbox-check-dis.gif");
}
#treeCaption {
height: 4em;
}
.captionWarning {
font-weight: bold;
}

View File

@ -0,0 +1,133 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
wizard {
-moz-appearance: none;
width: 55em;
height: 45em;
padding: 0;
background-color: Window;
}
.wizard-page-box {
-moz-appearance: none;
padding-left: 0;
padding-right: 0;
margin: 0;
}
wizardpage {
-moz-box-pack: center;
-moz-box-align: center;
margin: 0;
padding: 0 6em;
background-color: Window;
}
.wizard-header {
-moz-appearance: none;
border: none;
padding: 2em 0 1em 0;
text-align: center;
}
.wizard-header-label {
font-size: 24pt;
font-weight: normal;
}
.wizard-buttons {
background-color: rgba(0,0,0,0.1);
padding: 1em;
}
.wizard-buttons-separator {
visibility: collapse;
}
.wizard-header-icon {
visibility: collapse;
}
.accountChoiceButton {
font: menu;
}
.confirm {
border: 1px solid black;
padding: 1em;
border-radius: 5px;
}
/* Override the text-link style from global.css */
description > .text-link,
description > .text-link:focus {
margin: 0px;
padding: 0px;
border: 0px;
}
.success,
.error {
padding: 2px;
border-radius: 2px;
}
.error {
background-color: #FF0000 !important;
color: #FFFFFF !important;
}
.success {
background-color: #00FF00 !important;
}
.warning {
font-weight: bold;
font-size: 100%;
color: red;
}
.mainDesc {
font-weight: bold;
font-size: 100%;
}
.normal {
font-size: 100%;
}
.inputColumn {
margin-inline-end: 2px
}
.pin {
font-size: 18pt;
width: 4em;
text-align: center;
}
#passphraseHelpSpacer {
width: 0.5em;
}
#pairDeviceThrobber,
#login-throbber {
-moz-box-align: center;
}
#pairDeviceThrobber > image,
#login-throbber > image {
width: 16px;
list-style-image: url("chrome://global/skin/icons/loading.png");
}
#captchaFeedback {
visibility: hidden;
}
#successPageIcon {
/* TODO replace this with a 128px version (bug 591122) */
list-style-image: url("chrome://browser/skin/sync-32.png");
}

View File

@ -163,6 +163,9 @@ browser.jar:
skin/classic/browser/sync-horizontalbar@2x.png
skin/classic/browser/sync-mobileIcon.svg (../shared/sync-mobileIcon.svg)
skin/classic/browser/sync-notification-24.png
skin/classic/browser/syncSetup.css
skin/classic/browser/syncCommon.css
skin/classic/browser/syncQuota.css
skin/classic/browser/syncProgress-horizontalbar.png
skin/classic/browser/syncProgress-horizontalbar@2x.png
skin/classic/browser/Toolbar-background-noise.png (Toolbar-background-noise.png)

View File

@ -108,6 +108,19 @@ caption {
/* ----- SYNC PANE ----- */
#syncDesc {
padding: 0 8em;
}
#accountCaptionImage {
list-style-image: url("chrome://mozapps/skin/profile/profileicon.png");
}
#syncAddDeviceLabel {
margin-top: 1em;
margin-bottom: 1em;
}
#noFxaAccount {
line-height: 1.2em;
}

View File

@ -0,0 +1,55 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* The following are used by both sync/setup.xul and sync/genericChange.xul */
.status {
color: -moz-dialogtext;
}
.statusIcon {
margin-inline-start: 4px;
max-height: 16px;
max-width: 16px;
}
.statusIcon[status="active"] {
list-style-image: url("chrome://global/skin/icons/loading.png");
}
@media (min-resolution: 2dppx) {
.statusIcon[status="active"] {
list-style-image: url("chrome://global/skin/icons/loading@2x.png");
}
}
.statusIcon[status="error"] {
list-style-image: url("chrome://global/skin/icons/error-16.png");
}
.statusIcon[status="success"] {
list-style-image: url("chrome://global/skin/icons/information-16.png");
}
/* .data is only used by sync/genericChange.xul, but it seems unnecessary to have
a separate stylesheet for it. */
.data {
font-size: 90%;
font-weight: bold;
}
dialog#change-dialog {
width: 40em;
}
image#syncIcon {
list-style-image: url("chrome://browser/skin/sync-32.png");
}
#introText {
margin-top: 2px;
}
#feedback {
height: 2em;
}

View File

@ -0,0 +1,26 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#quotaDialog {
width: 33em;
height: 25em;
}
treechildren::-moz-tree-checkbox {
list-style-image: none;
}
treechildren::-moz-tree-checkbox(checked) {
list-style-image: url("chrome://global/skin/checkbox/cbox-check.gif");
}
treechildren::-moz-tree-checkbox(disabled) {
list-style-image: url("chrome://global/skin/checkbox/cbox-check-dis.gif");
}
#treeCaption {
height: 4em;
}
.captionWarning {
font-weight: bold;
}

View File

@ -0,0 +1,139 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
wizard {
-moz-appearance: none;
width: 55em;
height: 45em;
padding: 0;
background-color: Window;
}
.wizard-page-box {
-moz-appearance: none;
padding-left: 0;
padding-right: 0;
margin: 0;
}
wizardpage {
-moz-box-pack: center;
-moz-box-align: center;
margin: 0;
padding: 0 6em;
background-color: Window;
}
.wizard-header {
-moz-appearance: none;
border: none;
padding: 2em 0 1em 0;
text-align: center;
}
.wizard-header-label {
font-size: 24pt;
font-weight: normal;
}
.wizard-buttons {
background-color: rgba(0,0,0,0.1);
padding: 1em;
}
.wizard-buttons-separator {
visibility: collapse;
}
.wizard-header-icon {
visibility: collapse;
}
.accountChoiceButton {
font: menu;
}
.confirm {
border: 1px solid black;
padding: 1em;
border-radius: 5px;
}
/* Override the text-link style from global.css */
description > .text-link,
description > .text-link:focus {
margin: 0px;
padding: 0px;
border: 0px;
}
.success,
.error {
padding: 2px;
border-radius: 2px;
}
.error {
background-color: #FF0000 !important;
color: #FFFFFF !important;
}
.success {
background-color: #00FF00 !important;
}
.warning {
font-weight: bold;
font-size: 100%;
color: red;
}
.mainDesc {
font-weight: bold;
font-size: 100%;
}
.normal {
font-size: 100%;
}
.inputColumn {
margin-inline-end: 2px
}
.pin {
font-size: 18pt;
width: 4em;
text-align: center;
}
#passphraseHelpSpacer {
width: 0.5em;
}
#pairDeviceThrobber,
#login-throbber {
-moz-box-align: center;
}
#pairDeviceThrobber > image,
#login-throbber > image {
width: 16px;
list-style-image: url("chrome://global/skin/icons/loading.png");
}
@media (min-resolution: 2dppx) {
#pairDeviceThrobber > image,
#login-throbber > image {
list-style-image: url("chrome://global/skin/icons/loading@2x.png");
}
}
#captchaFeedback {
visibility: hidden;
}
#successPageIcon {
/* TODO replace this with a 128px version (bug 591122) */
list-style-image: url("chrome://browser/skin/sync-32.png");
}

View File

@ -842,6 +842,12 @@ toolbarpaletteitem[place="palette"] > toolbaritem > toolbarbutton {
list-style-image: url(chrome://browser/skin/syncProgress-horizontalbar.png);
}
#PanelUI-footer-fxa[fxastatus="migrate-signup"] > #PanelUI-fxa-status > #PanelUI-fxa-label,
#PanelUI-footer-fxa[fxastatus="migrate-verify"] > #PanelUI-fxa-status > #PanelUI-fxa-label {
list-style-image: url(chrome://browser/skin/warning.svg);
-moz-image-region: auto;
}
#PanelUI-customize {
list-style-image: url(chrome://browser/skin/menuPanel-customize.png);
}

View File

@ -248,7 +248,10 @@ treecol {
active vbox needs */
#historyPane:not([selectedIndex="1"]) > #historyDontRememberPane,
#historyPane:not([selectedIndex="2"]) > #historyCustomPane,
#weavePrefsDeck:not([selectedIndex="1"]) > #hasFxaAccount,
#weavePrefsDeck:not([selectedIndex="1"]) > #hasAccount,
#weavePrefsDeck:not([selectedIndex="2"]) > #needsUpdate,
#weavePrefsDeck:not([selectedIndex="3"]) > #noFxaAccount,
#weavePrefsDeck:not([selectedIndex="4"]) > #hasFxaAccount,
#fxaLoginStatus:not([selectedIndex="1"]) > #fxaLoginUnverified,
#fxaLoginStatus:not([selectedIndex="2"]) > #fxaLoginRejected {
visibility: collapse;
@ -263,8 +266,10 @@ description > html|a {
#weavePrefsDeck > vbox > label,
#weavePrefsDeck > vbox > groupbox,
#weavePrefsDeck > vbox > description,
#weavePrefsDeck > vbox > #pairDevice > label,
#weavePrefsDeck > #needsUpdate > hbox > #loginError,
#weavePrefsDeck > #hasFxaAccount > vbox > label,
#weavePrefsDeck > #hasFxaAccount > hbox > label {
#weavePrefsDeck > #hasFxaAccount > hbox:not(#tosPP-normal) > label {
/* no margin-inline-start for elements at the beginning of a line */
margin-inline-start: 0;
}

View File

@ -146,6 +146,9 @@ browser.jar:
skin/classic/browser/sync-horizontalbar-win7@2x.png
skin/classic/browser/sync-mobileIcon.svg (../shared/sync-mobileIcon.svg)
skin/classic/browser/sync-notification-24.png
skin/classic/browser/syncSetup.css
skin/classic/browser/syncCommon.css
skin/classic/browser/syncQuota.css
skin/classic/browser/syncProgress-horizontalbar.png
skin/classic/browser/syncProgress-horizontalbar@2x.png
skin/classic/browser/syncProgress-horizontalbar-win7.png

View File

@ -70,6 +70,23 @@
/* Sync Pane */
#syncDesc {
padding: 0 8em;
}
.syncGroupBox {
padding: 10px;
}
#accountCaptionImage {
list-style-image: url("chrome://mozapps/skin/profile/profileicon.png");
}
#syncAddDeviceLabel {
margin-top: 1em;
margin-bottom: 1em;
}
#noFxaAccount {
line-height: 1.2em;
}

View File

@ -0,0 +1,55 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* The following are used by both sync/setup.xul and sync/genericChange.xul */
.status {
color: -moz-dialogtext;
}
.statusIcon {
margin-inline-start: 4px;
max-height: 16px;
max-width: 16px;
}
.statusIcon[status="active"] {
list-style-image: url("chrome://global/skin/icons/loading.png");
}
@media (min-resolution: 1.1dppx) {
.statusIcon[status="active"] {
list-style-image: url("chrome://global/skin/icons/loading@2x.png");
}
}
.statusIcon[status="error"] {
list-style-image: url("chrome://global/skin/icons/error-16.png");
}
.statusIcon[status="success"] {
list-style-image: url("chrome://global/skin/icons/information-16.png");
}
/* .data is only used by sync/genericChange.xul, but it seems unnecessary to have
a separate stylesheet for it. */
.data {
font-size: 90%;
font-weight: bold;
}
dialog#change-dialog {
width: 40em;
}
image#syncIcon {
list-style-image: url("chrome://browser/skin/sync-32.png");
}
#introText {
margin-top: 2px;
}
#feedback {
height: 2em;
}

View File

@ -0,0 +1,26 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#quotaDialog {
width: 33em;
height: 25em;
}
treechildren::-moz-tree-checkbox {
list-style-image: none;
}
treechildren::-moz-tree-checkbox(checked) {
list-style-image: url("chrome://global/skin/checkbox/cbox-check.gif");
}
treechildren::-moz-tree-checkbox(disabled) {
list-style-image: url("chrome://global/skin/checkbox/cbox-check-dis.gif");
}
#treeCaption {
height: 4em;
}
.captionWarning {
font-weight: bold;
}

View File

@ -0,0 +1,145 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
wizard {
-moz-appearance: none;
width: 55em;
height: 45em;
padding: 0;
background-color: Window;
}
.wizard-page-box {
-moz-appearance: none;
padding-left: 0;
padding-right: 0;
margin: 0;
}
wizardpage {
-moz-box-pack: center;
-moz-box-align: center;
margin: 0;
padding: 0 6em;
background-color: Window;
}
.wizard-header {
-moz-appearance: none;
border: none;
padding: 2em 0 1em 0;
text-align: center;
}
.wizard-header-label {
font-size: 24pt;
font-weight: normal;
}
.wizard-buttons {
background-color: rgba(0,0,0,0.1);
padding: 1em;
}
.wizard-buttons-separator {
visibility: collapse;
}
.wizard-header-icon {
visibility: collapse;
}
.accountChoiceButton {
font: menu;
}
.confirm {
border: 1px solid black;
padding: 1em;
border-radius: 5px;
}
/* Override the text-link style from global.css */
description > .text-link,
description > .text-link:focus {
margin: 0px;
padding: 0px;
border: 0px;
}
.success,
.error {
padding: 2px;
border-radius: 2px;
}
.error {
background-color: #FF0000 !important;
color: #FFFFFF !important;
}
.success {
background-color: #00FF00 !important;
}
.warning {
font-weight: bold;
font-size: 100%;
color: red;
}
.mainDesc {
font-weight: bold;
font-size: 100%;
}
.normal {
font-size: 100%;
}
.inputColumn {
margin-inline-end: 2px
}
.pin {
font-size: 18pt;
width: 4em;
text-align: center;
}
#passphraseHelpSpacer {
width: 0.5em;
}
#pairDeviceThrobber,
#login-throbber {
-moz-box-align: center;
}
#pairDeviceThrobber > image,
#login-throbber > image {
width: 16px;
list-style-image: url("chrome://global/skin/icons/loading.png");
}
@media (min-resolution: 1.1dppx) {
#pairDeviceThrobber > image,
#login-throbber > image {
list-style-image: url("chrome://global/skin/icons/loading@2x.png");
}
}
#captchaFeedback {
visibility: hidden;
}
#successPageIcon {
/* TODO replace this with a 128px version (bug 591122) */
list-style-image: url("chrome://browser/skin/sync-32.png");
}
#tosDesc {
margin-left: -7px;
margin-bottom: 3px;
}

View File

@ -213,6 +213,7 @@
@BINPATH@/components/rdf.xpt
@BINPATH@/components/satchel.xpt
@BINPATH@/components/saxparser.xpt
@BINPATH@/components/services-crypto-component.xpt
@BINPATH@/components/captivedetect.xpt
@BINPATH@/components/shistory.xpt
@BINPATH@/components/spellchecker.xpt

View File

@ -157,3 +157,16 @@ function uninstallFakePAC() {
_("Uninstalling fake PAC.");
MockRegistrar.unregister(fakePACCID);
}
// Many tests do service.startOver() and don't expect the provider type to
// change (whereas by default, a startOver will do exactly that so FxA is
// subsequently used). The tests that know how to deal with
// the Firefox Accounts identity hack things to ensure that still works.
function ensureStartOverKeepsIdentity() {
Cu.import("resource://gre/modules/Services.jsm");
Services.prefs.setBoolPref("services.sync-testing.startOverKeepIdentity", true);
do_register_cleanup(function() {
Services.prefs.clearUserPref("services.sync-testing.startOverKeepIdentity");
});
}
ensureStartOverKeepsIdentity();

View File

@ -0,0 +1,21 @@
# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
# vim: set filetype=python:
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
XPCSHELL_TESTS_MANIFESTS += ['tests/unit/xpcshell.ini']
XPIDL_SOURCES += [
'nsIIdentityCryptoService.idl',
'nsISyncJPAKE.idl',
]
XPIDL_MODULE = 'services-crypto-component'
SOURCES += [
'IdentityCryptoService.cpp',
'nsSyncJPAKE.cpp',
]
FINAL_LIBRARY = 'xul'

View File

@ -0,0 +1,103 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsISupports.idl"
[scriptable, uuid(5ab02a98-5122-4b90-93cd-f259c4b42e3a)]
interface nsISyncJPAKE : nsISupports
{
/**
* Perform first round of the JPAKE exchange.
*
* @param aSignerID
* String identifying the signer.
* @param aGX1
* Schnorr signature value g^x1, in hex representation.
* @param aGV1
* Schnorr signature value g^v1 (v1 is a random value), in hex
* representation.
* @param aR1
* Schnorr signature value r1 = v1 - x1 * h, in hex representation.
* @param aGX2
* Schnorr signature value g^x2, in hex representation.
* @param aGV2
* Schnorr signature value g^v2 (v2 is a random value), in hex
* representation.
* @param aR2
* Schnorr signature value r2 = v2 - x2 * h, in hex representation.
*/
void round1(in ACString aSignerID,
out ACString aGX1,
out ACString aGV1,
out ACString aR1,
out ACString aGX2,
out ACString aGV2,
out ACString aR2);
/**
* Perform second round of the JPAKE exchange.
*
* @param aPeerID
* String identifying the peer.
* @param aPIN
* String containing the weak secret (PIN).
* @param aGX3
* Schnorr signature value g^x3, in hex representation.
* @param aGV3
* Schnorr signature value g^v3 (v3 is a random value), in hex
* representation.
* @param aR3
* Schnorr signature value r3 = v3 - x3 * h, in hex representation.
* @param aGX4
* Schnorr signature value g^x4, in hex representation.
* @param aGV4
* Schnorr signature value g^v4 (v4 is a random value), in hex
* representation.
* @param aR4
* Schnorr signature value r4 = v4 - x4 * h, in hex representation.
* @param aA
* Schnorr signature value A, in hex representation.
* @param aGVA
* Schnorr signature value g^va (va is a random value), in hex
* representation.
* @param aRA
* Schnorr signature value ra = va - xa * h, in hex representation.
*/
void round2(in ACString aPeerID,
in ACString aPIN,
in ACString aGX3,
in ACString aGV3,
in ACString aR3,
in ACString aGX4,
in ACString aGV4,
in ACString aR4,
out ACString aA,
out ACString aGVA,
out ACString aRA);
/**
* Perform the final step of the JPAKE exchange. This will compute
* the key and expand the key to two keys, an AES256 encryption key
* and a 256 bit HMAC key. It returns a key confirmation value
* (SHA256d of the key) and the encryption and HMAC keys.
*
* @param aB
* Schnorr signature value B, in hex representation.
* @param aGVB
* Schnorr signature value g^vb (vb is a random value), in hex
* representation.
* @param aRB
* Schnorr signature value rb = vb - xb * h, in hex representation.
* @param aAES256Key
* The AES 256 encryption key, in base64 representation.
* @param aHMAC256Key
* The 256 bit HMAC key, in base64 representation.
*/
void final(in ACString aB,
in ACString aGVB,
in ACString aRB,
in ACString aHkdfInfo,
out ACString aAES256Key,
out ACString aHMAC256Key);
};

View File

@ -0,0 +1,484 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsSyncJPAKE.h"
#include "base64.h"
#include "keyhi.h"
#include "mozilla/ModuleUtils.h"
#include "mozilla/Move.h"
#include "nsDebug.h"
#include "nsError.h"
#include "nsString.h"
#include "nscore.h"
#include "pk11pub.h"
#include "pkcs11.h"
#include "secerr.h"
#include "secmodt.h"
#include "secport.h"
using mozilla::fallible;
static bool
hex_from_2char(const unsigned char *c2, unsigned char *byteval)
{
int i;
unsigned char offset;
*byteval = 0;
for (i=0; i<2; i++) {
if (c2[i] >= '0' && c2[i] <= '9') {
offset = c2[i] - '0';
*byteval |= offset << 4*(1-i);
} else if (c2[i] >= 'a' && c2[i] <= 'f') {
offset = c2[i] - 'a';
*byteval |= (offset + 10) << 4*(1-i);
} else if (c2[i] >= 'A' && c2[i] <= 'F') {
offset = c2[i] - 'A';
*byteval |= (offset + 10) << 4*(1-i);
} else {
return false;
}
}
return true;
}
static bool
fromHex(const char * str, unsigned char * p, size_t sLen)
{
size_t i;
if (sLen & 1)
return false;
for (i = 0; i < sLen / 2; ++i) {
if (!hex_from_2char((const unsigned char *) str + (2*i),
(unsigned char *) p + i)) {
return false;
}
}
return true;
}
static nsresult
fromHexString(const nsACString & str, unsigned char * p, size_t pMaxLen)
{
char * strData = (char *) str.Data();
unsigned len = str.Length();
NS_ENSURE_ARG(len / 2 <= pMaxLen);
if (!fromHex(strData, p, len)) {
return NS_ERROR_INVALID_ARG;
}
return NS_OK;
}
static bool
toHexString(const unsigned char * str, unsigned len, nsACString & out)
{
static const char digits[] = "0123456789ABCDEF";
if (!out.SetCapacity(2 * len, fallible))
return false;
out.SetLength(0);
for (unsigned i = 0; i < len; ++i) {
out.Append(digits[str[i] >> 4]);
out.Append(digits[str[i] & 0x0f]);
}
return true;
}
static nsresult
mapErrno()
{
int err = PORT_GetError();
switch (err) {
case SEC_ERROR_NO_MEMORY: return NS_ERROR_OUT_OF_MEMORY;
default: return NS_ERROR_UNEXPECTED;
}
}
#define NUM_ELEM(x) (sizeof(x) / sizeof (x)[0])
static const char p[] =
"90066455B5CFC38F9CAA4A48B4281F292C260FEEF01FD61037E56258A7795A1C"
"7AD46076982CE6BB956936C6AB4DCFE05E6784586940CA544B9B2140E1EB523F"
"009D20A7E7880E4E5BFA690F1B9004A27811CD9904AF70420EEFD6EA11EF7DA1"
"29F58835FF56B89FAA637BC9AC2EFAAB903402229F491D8D3485261CD068699B"
"6BA58A1DDBBEF6DB51E8FE34E8A78E542D7BA351C21EA8D8F1D29F5D5D159394"
"87E27F4416B0CA632C59EFD1B1EB66511A5A0FBF615B766C5862D0BD8A3FE7A0"
"E0DA0FB2FE1FCB19E8F9996A8EA0FCCDE538175238FC8B0EE6F29AF7F642773E"
"BE8CD5402415A01451A840476B2FCEB0E388D30D4B376C37FE401C2A2C2F941D"
"AD179C540C1C8CE030D460C4D983BE9AB0B20F69144C1AE13F9383EA1C08504F"
"B0BF321503EFE43488310DD8DC77EC5B8349B8BFE97C2C560EA878DE87C11E3D"
"597F1FEA742D73EEC7F37BE43949EF1A0D15C3F3E3FC0A8335617055AC91328E"
"C22B50FC15B941D3D1624CD88BC25F3E941FDDC6200689581BFEC416B4B2CB73";
static const char q[] =
"CFA0478A54717B08CE64805B76E5B14249A77A4838469DF7F7DC987EFCCFB11D";
static const char g[] =
"5E5CBA992E0A680D885EB903AEA78E4A45A469103D448EDE3B7ACCC54D521E37"
"F84A4BDD5B06B0970CC2D2BBB715F7B82846F9A0C393914C792E6A923E2117AB"
"805276A975AADB5261D91673EA9AAFFEECBFA6183DFCB5D3B7332AA19275AFA1"
"F8EC0B60FB6F66CC23AE4870791D5982AAD1AA9485FD8F4A60126FEB2CF05DB8"
"A7F0F09B3397F3937F2E90B9E5B9C9B6EFEF642BC48351C46FB171B9BFA9EF17"
"A961CE96C7E7A7CC3D3D03DFAD1078BA21DA425198F07D2481622BCE45969D9C"
"4D6063D72AB7A0F08B2F49A7CC6AF335E08C4720E31476B67299E231F8BD90B3"
"9AC3AE3BE0C6B6CACEF8289A2E2873D58E51E029CAFBD55E6841489AB66B5B4B"
"9BA6E2F784660896AFF387D92844CCB8B69475496DE19DA2E58259B090489AC8"
"E62363CDF82CFD8EF2A427ABCD65750B506F56DDE3B988567A88126B914D7828"
"E2B63A6D7ED0747EC59E0E0A23CE7D8A74C1D2C2A7AFB6A29799620F00E11C33"
"787F7DED3B30E1A22D09F1FBDA1ABBBFBF25CAE05A13F812E34563F99410E73B";
NS_IMETHODIMP nsSyncJPAKE::Round1(const nsACString & aSignerID,
nsACString & aGX1,
nsACString & aGV1,
nsACString & aR1,
nsACString & aGX2,
nsACString & aGV2,
nsACString & aR2)
{
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown()) {
return NS_ERROR_NOT_AVAILABLE;
}
NS_ENSURE_STATE(round == JPAKENotStarted);
NS_ENSURE_STATE(key == nullptr);
static CK_MECHANISM_TYPE mechanisms[] = {
CKM_NSS_JPAKE_ROUND1_SHA256,
CKM_NSS_JPAKE_ROUND2_SHA256,
CKM_NSS_JPAKE_FINAL_SHA256
};
UniquePK11SlotInfo slot(PK11_GetBestSlotMultiple(mechanisms,
NUM_ELEM(mechanisms),
nullptr));
NS_ENSURE_STATE(slot != nullptr);
CK_BYTE pBuf[(NUM_ELEM(p) - 1) / 2];
CK_BYTE qBuf[(NUM_ELEM(q) - 1) / 2];
CK_BYTE gBuf[(NUM_ELEM(g) - 1) / 2];
CK_KEY_TYPE keyType = CKK_NSS_JPAKE_ROUND1;
NS_ENSURE_STATE(fromHex(p, pBuf, (NUM_ELEM(p) - 1)));
NS_ENSURE_STATE(fromHex(q, qBuf, (NUM_ELEM(q) - 1)));
NS_ENSURE_STATE(fromHex(g, gBuf, (NUM_ELEM(g) - 1)));
CK_ATTRIBUTE keyTemplate[] = {
{ CKA_NSS_JPAKE_SIGNERID, (CK_BYTE *) aSignerID.Data(),
aSignerID.Length() },
{ CKA_KEY_TYPE, &keyType, sizeof keyType },
{ CKA_PRIME, pBuf, sizeof pBuf },
{ CKA_SUBPRIME, qBuf, sizeof qBuf },
{ CKA_BASE, gBuf, sizeof gBuf }
};
CK_BYTE gx1Buf[NUM_ELEM(p) / 2];
CK_BYTE gv1Buf[NUM_ELEM(p) / 2];
CK_BYTE r1Buf [NUM_ELEM(p) / 2];
CK_BYTE gx2Buf[NUM_ELEM(p) / 2];
CK_BYTE gv2Buf[NUM_ELEM(p) / 2];
CK_BYTE r2Buf [NUM_ELEM(p) / 2];
CK_NSS_JPAKERound1Params rp = {
{ gx1Buf, sizeof gx1Buf, gv1Buf, sizeof gv1Buf, r1Buf, sizeof r1Buf },
{ gx2Buf, sizeof gx2Buf, gv2Buf, sizeof gv2Buf, r2Buf, sizeof r2Buf }
};
SECItem paramsItem;
paramsItem.data = (unsigned char *) &rp;
paramsItem.len = sizeof rp;
key = UniquePK11SymKey(
PK11_KeyGenWithTemplate(slot.get(), CKM_NSS_JPAKE_ROUND1_SHA256,
CKM_NSS_JPAKE_ROUND1_SHA256, &paramsItem,
keyTemplate, NUM_ELEM(keyTemplate), nullptr));
nsresult rv = key != nullptr
? NS_OK
: mapErrno();
if (rv == NS_OK) {
NS_ENSURE_TRUE(toHexString(rp.gx1.pGX, rp.gx1.ulGXLen, aGX1) &&
toHexString(rp.gx1.pGV, rp.gx1.ulGVLen, aGV1) &&
toHexString(rp.gx1.pR, rp.gx1.ulRLen, aR1) &&
toHexString(rp.gx2.pGX, rp.gx2.ulGXLen, aGX2) &&
toHexString(rp.gx2.pGV, rp.gx2.ulGVLen, aGV2) &&
toHexString(rp.gx2.pR, rp.gx2.ulRLen, aR2),
NS_ERROR_OUT_OF_MEMORY);
round = JPAKEBeforeRound2;
}
return rv;
}
NS_IMETHODIMP nsSyncJPAKE::Round2(const nsACString & aPeerID,
const nsACString & aPIN,
const nsACString & aGX3,
const nsACString & aGV3,
const nsACString & aR3,
const nsACString & aGX4,
const nsACString & aGV4,
const nsACString & aR4,
nsACString & aA,
nsACString & aGVA,
nsACString & aRA)
{
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown()) {
return NS_ERROR_NOT_AVAILABLE;
}
NS_ENSURE_STATE(round == JPAKEBeforeRound2);
NS_ENSURE_STATE(key != nullptr);
NS_ENSURE_ARG(!aPeerID.IsEmpty());
/* PIN cannot be equal to zero when converted to a bignum. NSS 3.12.9 J-PAKE
assumes that the caller has already done this check. Future versions of
NSS J-PAKE will do this check internally. See Bug 609068 Comment 4 */
bool foundNonZero = false;
for (size_t i = 0; i < aPIN.Length(); ++i) {
if (aPIN[i] != 0) {
foundNonZero = true;
break;
}
}
NS_ENSURE_ARG(foundNonZero);
CK_BYTE gx3Buf[NUM_ELEM(p)/2], gv3Buf[NUM_ELEM(p)/2], r3Buf [NUM_ELEM(p)/2];
CK_BYTE gx4Buf[NUM_ELEM(p)/2], gv4Buf[NUM_ELEM(p)/2], r4Buf [NUM_ELEM(p)/2];
CK_BYTE gxABuf[NUM_ELEM(p)/2], gvABuf[NUM_ELEM(p)/2], rABuf [NUM_ELEM(p)/2];
nsresult rv = fromHexString(aGX3, gx3Buf, sizeof gx3Buf);
if (rv == NS_OK) rv = fromHexString(aGV3, gv3Buf, sizeof gv3Buf);
if (rv == NS_OK) rv = fromHexString(aR3, r3Buf, sizeof r3Buf);
if (rv == NS_OK) rv = fromHexString(aGX4, gx4Buf, sizeof gx4Buf);
if (rv == NS_OK) rv = fromHexString(aGV4, gv4Buf, sizeof gv4Buf);
if (rv == NS_OK) rv = fromHexString(aR4, r4Buf, sizeof r4Buf);
if (rv != NS_OK)
return rv;
CK_NSS_JPAKERound2Params rp;
rp.pSharedKey = (CK_BYTE *) aPIN.Data();
rp.ulSharedKeyLen = aPIN.Length();
rp.gx3.pGX = gx3Buf; rp.gx3.ulGXLen = aGX3.Length() / 2;
rp.gx3.pGV = gv3Buf; rp.gx3.ulGVLen = aGV3.Length() / 2;
rp.gx3.pR = r3Buf; rp.gx3.ulRLen = aR3 .Length() / 2;
rp.gx4.pGX = gx4Buf; rp.gx4.ulGXLen = aGX4.Length() / 2;
rp.gx4.pGV = gv4Buf; rp.gx4.ulGVLen = aGV4.Length() / 2;
rp.gx4.pR = r4Buf; rp.gx4.ulRLen = aR4 .Length() / 2;
rp.A.pGX = gxABuf; rp.A .ulGXLen = sizeof gxABuf;
rp.A.pGV = gvABuf; rp.A .ulGVLen = sizeof gxABuf;
rp.A.pR = rABuf; rp.A .ulRLen = sizeof gxABuf;
// Bug 629090: NSS 3.12.9 J-PAKE fails to check that gx^4 != 1, so check here.
bool gx4Good = false;
for (unsigned i = 0; i < rp.gx4.ulGXLen; ++i) {
if (rp.gx4.pGX[i] > 1 || (rp.gx4.pGX[i] != 0 && i < rp.gx4.ulGXLen - 1)) {
gx4Good = true;
break;
}
}
NS_ENSURE_ARG(gx4Good);
SECItem paramsItem;
paramsItem.data = (unsigned char *) &rp;
paramsItem.len = sizeof rp;
CK_KEY_TYPE keyType = CKK_NSS_JPAKE_ROUND2;
CK_ATTRIBUTE keyTemplate[] = {
{ CKA_NSS_JPAKE_PEERID, (CK_BYTE *) aPeerID.Data(), aPeerID.Length(), },
{ CKA_KEY_TYPE, &keyType, sizeof keyType }
};
UniquePK11SymKey newKey(PK11_DeriveWithTemplate(key.get(),
CKM_NSS_JPAKE_ROUND2_SHA256,
&paramsItem,
CKM_NSS_JPAKE_FINAL_SHA256,
CKA_DERIVE, 0,
keyTemplate,
NUM_ELEM(keyTemplate),
false));
if (newKey != nullptr) {
if (toHexString(rp.A.pGX, rp.A.ulGXLen, aA) &&
toHexString(rp.A.pGV, rp.A.ulGVLen, aGVA) &&
toHexString(rp.A.pR, rp.A.ulRLen, aRA)) {
round = JPAKEAfterRound2;
key = Move(newKey);
return NS_OK;
} else {
rv = NS_ERROR_OUT_OF_MEMORY;
}
} else {
rv = mapErrno();
}
return rv;
}
static nsresult
setBase64(const unsigned char * data, unsigned len, nsACString & out)
{
nsresult rv = NS_OK;
const char * base64 = BTOA_DataToAscii(data, len);
if (base64 != nullptr) {
size_t len = PORT_Strlen(base64);
if (out.SetCapacity(len, fallible)) {
out.SetLength(0);
out.Append(base64, len);
} else {
rv = NS_ERROR_OUT_OF_MEMORY;
}
PORT_Free((void*) base64);
} else {
rv = NS_ERROR_OUT_OF_MEMORY;
}
return rv;
}
static nsresult
base64KeyValue(PK11SymKey * key, nsACString & keyString)
{
nsresult rv = NS_OK;
if (PK11_ExtractKeyValue(key) == SECSuccess) {
const SECItem * value = PK11_GetKeyData(key);
rv = value != nullptr && value->data != nullptr && value->len > 0
? setBase64(value->data, value->len, keyString)
: NS_ERROR_UNEXPECTED;
} else {
rv = mapErrno();
}
return rv;
}
static nsresult
extractBase64KeyValue(UniquePK11SymKey & keyBlock, CK_ULONG bitPosition,
CK_MECHANISM_TYPE destMech, int keySize,
nsACString & keyString)
{
SECItem paramsItem;
paramsItem.data = (CK_BYTE *) &bitPosition;
paramsItem.len = sizeof bitPosition;
PK11SymKey * key = PK11_Derive(keyBlock.get(), CKM_EXTRACT_KEY_FROM_KEY,
&paramsItem, destMech,
CKA_SIGN, keySize);
if (key == nullptr)
return mapErrno();
nsresult rv = base64KeyValue(key, keyString);
PK11_FreeSymKey(key);
return rv;
}
NS_IMETHODIMP nsSyncJPAKE::Final(const nsACString & aB,
const nsACString & aGVB,
const nsACString & aRB,
const nsACString & aHKDFInfo,
nsACString & aAES256Key,
nsACString & aHMAC256Key)
{
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown()) {
return NS_ERROR_NOT_AVAILABLE;
}
static const unsigned AES256_KEY_SIZE = 256 / 8;
static const unsigned HMAC_SHA256_KEY_SIZE = 256 / 8;
CK_EXTRACT_PARAMS aesBitPosition = 0;
CK_EXTRACT_PARAMS hmacBitPosition = aesBitPosition + (AES256_KEY_SIZE * 8);
NS_ENSURE_STATE(round == JPAKEAfterRound2);
NS_ENSURE_STATE(key != nullptr);
CK_BYTE gxBBuf[NUM_ELEM(p)/2], gvBBuf[NUM_ELEM(p)/2], rBBuf [NUM_ELEM(p)/2];
nsresult rv = fromHexString(aB, gxBBuf, sizeof gxBBuf);
if (rv == NS_OK) rv = fromHexString(aGVB, gvBBuf, sizeof gvBBuf);
if (rv == NS_OK) rv = fromHexString(aRB, rBBuf, sizeof rBBuf);
if (rv != NS_OK)
return rv;
CK_NSS_JPAKEFinalParams rp;
rp.B.pGX = gxBBuf; rp.B.ulGXLen = aB .Length() / 2;
rp.B.pGV = gvBBuf; rp.B.ulGVLen = aGVB.Length() / 2;
rp.B.pR = rBBuf; rp.B.ulRLen = aRB .Length() / 2;
SECItem paramsItem;
paramsItem.data = (unsigned char *) &rp;
paramsItem.len = sizeof rp;
UniquePK11SymKey keyMaterial(PK11_Derive(key.get(), CKM_NSS_JPAKE_FINAL_SHA256,
&paramsItem, CKM_NSS_HKDF_SHA256,
CKA_DERIVE, 0));
UniquePK11SymKey keyBlock;
if (keyMaterial == nullptr)
rv = mapErrno();
if (rv == NS_OK) {
CK_NSS_HKDFParams hkdfParams;
hkdfParams.bExtract = CK_TRUE;
hkdfParams.pSalt = nullptr;
hkdfParams.ulSaltLen = 0;
hkdfParams.bExpand = CK_TRUE;
hkdfParams.pInfo = (CK_BYTE *) aHKDFInfo.Data();
hkdfParams.ulInfoLen = aHKDFInfo.Length();
paramsItem.data = (unsigned char *) &hkdfParams;
paramsItem.len = sizeof hkdfParams;
keyBlock = UniquePK11SymKey(
PK11_Derive(keyMaterial.get(), CKM_NSS_HKDF_SHA256, &paramsItem,
CKM_EXTRACT_KEY_FROM_KEY, CKA_DERIVE,
AES256_KEY_SIZE + HMAC_SHA256_KEY_SIZE));
if (keyBlock == nullptr)
rv = mapErrno();
}
if (rv == NS_OK) {
rv = extractBase64KeyValue(keyBlock, aesBitPosition, CKM_AES_CBC,
AES256_KEY_SIZE, aAES256Key);
}
if (rv == NS_OK) {
rv = extractBase64KeyValue(keyBlock, hmacBitPosition, CKM_SHA256_HMAC,
HMAC_SHA256_KEY_SIZE, aHMAC256Key);
}
if (rv == NS_OK) {
SECStatus srv = PK11_ExtractKeyValue(keyMaterial.get());
NS_ENSURE_TRUE(srv == SECSuccess, NS_ERROR_UNEXPECTED);
SECItem * keyMaterialBytes = PK11_GetKeyData(keyMaterial.get());
NS_ENSURE_TRUE(keyMaterialBytes != nullptr, NS_ERROR_UNEXPECTED);
}
return rv;
}
NS_GENERIC_FACTORY_CONSTRUCTOR(nsSyncJPAKE)
NS_DEFINE_NAMED_CID(NS_SYNCJPAKE_CID);
nsSyncJPAKE::nsSyncJPAKE() : round(JPAKENotStarted), key(nullptr) { }
nsSyncJPAKE::~nsSyncJPAKE()
{
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown()) {
return;
}
destructorSafeDestroyNSSReference();
shutdown(ShutdownCalledFrom::Object);
}
void
nsSyncJPAKE::virtualDestroyNSSReference()
{
destructorSafeDestroyNSSReference();
}
void
nsSyncJPAKE::destructorSafeDestroyNSSReference()
{
key = nullptr;
}
static const mozilla::Module::CIDEntry kServicesCryptoCIDs[] = {
{ &kNS_SYNCJPAKE_CID, false, nullptr, nsSyncJPAKEConstructor },
{ nullptr }
};
static const mozilla::Module::ContractIDEntry kServicesCryptoContracts[] = {
{ NS_SYNCJPAKE_CONTRACTID, &kNS_SYNCJPAKE_CID },
{ nullptr }
};
static const mozilla::Module kServicesCryptoModule = {
mozilla::Module::kVersion,
kServicesCryptoCIDs,
kServicesCryptoContracts
};
NSMODULE_DEFN(nsServicesCryptoModule) = &kServicesCryptoModule;

View File

@ -0,0 +1,38 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef nsSyncJPAKE_h__
#define nsSyncJPAKE_h__
#include "ScopedNSSTypes.h"
#include "nsISyncJPAKE.h"
#include "nsNSSShutDown.h"
#define NS_SYNCJPAKE_CONTRACTID \
"@mozilla.org/services-crypto/sync-jpake;1"
#define NS_SYNCJPAKE_CID \
{0x0b9721c0, 0x1805, 0x47c3, {0x86, 0xce, 0x68, 0x13, 0x79, 0x5a, 0x78, 0x3f}}
using namespace mozilla;
class nsSyncJPAKE : public nsISyncJPAKE
, public nsNSSShutDownObject
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISYNCJPAKE
nsSyncJPAKE();
protected:
virtual ~nsSyncJPAKE();
private:
virtual void virtualDestroyNSSReference() override;
void destructorSafeDestroyNSSReference();
enum { JPAKENotStarted, JPAKEBeforeRound2, JPAKEAfterRound2 } round;
UniquePK11SymKey key;
};
NS_IMPL_ISUPPORTS(nsSyncJPAKE, nsISyncJPAKE)
#endif // nsSyncJPAKE_h__

View File

@ -0,0 +1,289 @@
var Cc = Components.classes;
var Ci = Components.interfaces;
// Ensure PSM is initialized.
Cc["@mozilla.org/psm;1"].getService(Ci.nsISupports);
function do_check_throws(func) {
let have_error = false;
try {
func();
} catch (ex) {
dump("Was expecting an exception. Caught: " + ex + "\n");
have_error = true;
}
do_check_true(have_error);
}
function test_success() {
let a = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
.createInstance(Ci.nsISyncJPAKE);
let b = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
.createInstance(Ci.nsISyncJPAKE);
let a_gx1 = {};
let a_gv1 = {};
let a_r1 = {};
let a_gx2 = {};
let a_gv2 = {};
let a_r2 = {};
let b_gx1 = {};
let b_gv1 = {};
let b_r1 = {};
let b_gx2 = {};
let b_gv2 = {};
let b_r2 = {};
a.round1("alice", a_gx1, a_gv1, a_r1, a_gx2, a_gv2, a_r2);
b.round1("bob", b_gx1, b_gv1, b_r1, b_gx2, b_gv2, b_r2);
let a_A = {};
let a_gva = {};
let a_ra = {};
let b_A = {};
let b_gva = {};
let b_ra = {};
a.round2("bob", "sekrit", b_gx1.value, b_gv1.value, b_r1.value,
b_gx2.value, b_gv2.value, b_r2.value, a_A, a_gva, a_ra);
b.round2("alice", "sekrit", a_gx1.value, a_gv1.value, a_r1.value,
a_gx2.value, a_gv2.value, a_r2.value, b_A, b_gva, b_ra);
let a_aes = {};
let a_hmac = {};
let b_aes = {};
let b_hmac = {};
a.final(b_A.value, b_gva.value, b_ra.value, "ohai", a_aes, a_hmac);
b.final(a_A.value, a_gva.value, a_ra.value, "ohai", b_aes, b_hmac);
do_check_eq(a_aes.value, b_aes.value);
do_check_eq(a_hmac.value, b_hmac.value);
}
function test_failure(modlen) {
let a = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
.createInstance(Ci.nsISyncJPAKE);
let b = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
.createInstance(Ci.nsISyncJPAKE);
let a_gx1 = {};
let a_gv1 = {};
let a_r1 = {};
let a_gx2 = {};
let a_gv2 = {};
let a_r2 = {};
let b_gx1 = {};
let b_gv1 = {};
let b_r1 = {};
let b_gx2 = {};
let b_gv2 = {};
let b_r2 = {};
a.round1("alice", a_gx1, a_gv1, a_r1, a_gx2, a_gv2, a_r2);
b.round1("bob", b_gx1, b_gv1, b_r1, b_gx2, b_gv2, b_r2);
let a_A = {};
let a_gva = {};
let a_ra = {};
let b_A = {};
let b_gva = {};
let b_ra = {};
// Note how the PINs are different (secret vs. sekrit)
a.round2("bob", "secret", b_gx1.value, b_gv1.value, b_r1.value,
b_gx2.value, b_gv2.value, b_r2.value, a_A, a_gva, a_ra);
b.round2("alice", "sekrit", a_gx1.value, a_gv1.value, a_r1.value,
a_gx2.value, a_gv2.value, a_r2.value, b_A, b_gva, b_ra);
let a_aes = {};
let a_hmac = {};
let b_aes = {};
let b_hmac = {};
a.final(b_A.value, b_gva.value, b_ra.value, "ohai", a_aes, a_hmac);
b.final(a_A.value, a_gva.value, a_ra.value, "ohai", b_aes, b_hmac);
do_check_neq(a_aes.value, b_aes.value);
do_check_neq(a_hmac.value, b_hmac.value);
}
function test_same_signerids() {
let a = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
.createInstance(Ci.nsISyncJPAKE);
let b = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
.createInstance(Ci.nsISyncJPAKE);
let gx1 = {};
let gv1 = {};
let r1 = {};
let gx2 = {};
let gv2 = {};
let r2 = {};
a.round1("alice", {}, {}, {}, {}, {}, {});
b.round1("alice", gx1, gv1, r1, gx2, gv2, r2);
do_check_throws(function() {
a.round2("alice", "sekrit", gx1.value, gv1.value, r1.value,
gx2.value, gv2.value, r2.value, {}, {}, {});
});
}
function test_bad_zkp() {
let a = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
.createInstance(Ci.nsISyncJPAKE);
let b = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
.createInstance(Ci.nsISyncJPAKE);
let gx1 = {};
let gv1 = {};
let r1 = {};
let gx2 = {};
let gv2 = {};
let r2 = {};
a.round1("alice", {}, {}, {}, {}, {}, {});
b.round1("bob", gx1, gv1, r1, gx2, gv2, r2);
do_check_throws(function() {
a.round2("invalid", "sekrit", gx1.value, gv1.value, r1.value,
gx2.value, gv2.value, r2.value, {}, {}, {});
});
}
function test_x4_zero() {
// The PKCS#11 API for J-PAKE does not allow us to choose any of the nonces.
// In order to test the defence against x4 (mod p) == 1, we had to generate
// our own signed nonces using a the FreeBL JPAKE_Sign function directly.
// To verify the signatures are accurate, pass the given value of R as the
// "testRandom" parameter to FreeBL's JPAKE_Sign, along with the given values
// for X and GX, using signerID "alice". Then verify that each GV returned
// from JPAKE_Sign matches the value specified here.
let test = function(badGX, badX_GV, badX_R) {
let a = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
.createInstance(Ci.nsISyncJPAKE);
let b = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
.createInstance(Ci.nsISyncJPAKE);
let a_gx1 = {};
let a_gv1 = {};
let a_r1 = {};
let a_gx2 = {};
let a_gv2 = {};
let a_r2 = {};
let b_gx1 = {};
let b_gv1 = {};
let b_r1 = {};
let b_gx2 = {};
let b_gv2 = {};
let b_r2 = {};
a.round1("alice", a_gx1, a_gv1, a_r1, a_gx2, a_gv2, a_r2);
b.round1("bob", b_gx1, b_gv1, b_r1, b_gx2, b_gv2, b_r2);
// Replace the g^x2 generated by A with the given illegal value.
a_gx2.value = badGX;
a_gv2.value = badX_GV;
a_r2.value = badX_R;
let b_A = {};
let b_gva = {};
let b_ra = {};
do_check_throws(function() {
b.round2("alice", "secret", a_gx1.value, a_gv1.value, a_r1.value,
a_gx2.value, a_gv2.value, a_r2.value, b_A, b_gva, b_ra);
});
};
// g^x is NIST 3072's p + 1, (p + 1) mod p == 1, x == 0
test("90066455B5CFC38F9CAA4A48B4281F292C260FEEF01FD61037E56258A7795A1C"
+ "7AD46076982CE6BB956936C6AB4DCFE05E6784586940CA544B9B2140E1EB523F"
+ "009D20A7E7880E4E5BFA690F1B9004A27811CD9904AF70420EEFD6EA11EF7DA1"
+ "29F58835FF56B89FAA637BC9AC2EFAAB903402229F491D8D3485261CD068699B"
+ "6BA58A1DDBBEF6DB51E8FE34E8A78E542D7BA351C21EA8D8F1D29F5D5D159394"
+ "87E27F4416B0CA632C59EFD1B1EB66511A5A0FBF615B766C5862D0BD8A3FE7A0"
+ "E0DA0FB2FE1FCB19E8F9996A8EA0FCCDE538175238FC8B0EE6F29AF7F642773E"
+ "BE8CD5402415A01451A840476B2FCEB0E388D30D4B376C37FE401C2A2C2F941D"
+ "AD179C540C1C8CE030D460C4D983BE9AB0B20F69144C1AE13F9383EA1C08504F"
+ "B0BF321503EFE43488310DD8DC77EC5B8349B8BFE97C2C560EA878DE87C11E3D"
+ "597F1FEA742D73EEC7F37BE43949EF1A0D15C3F3E3FC0A8335617055AC91328E"
+ "C22B50FC15B941D3D1624CD88BC25F3E941FDDC6200689581BFEC416B4B2CB74",
"5386107A0DD4A96ECF8D9BCF864BDE23AAEF13351F5550D777A32C1FEC165ED67AE51"
+ "66C3876AABC1FED1A0993754F3AEE256530F529548F8FE010BC0D070175569845"
+ "CF009AD24BC897A9CA1F18E1A9CE421DD54FD93AB528BC2594B47791713165276"
+ "7B76903190C3DCD2076FEC1E61FFFC32D1B07273B06EA2889E66FCBFD41FE8984"
+ "5FCE36056B09D1F20E58BB6BAA07A32796F11998BEF0AB3D387E2FB4FE3073FEB"
+ "634BA91709010A70DA29C06F8F92D638C4F158680EAFEB5E0E323BD7DACB671C0"
+ "BA3EDEEAB5CAA243CABAB28E7205AC9A0AAEAFE132635DAC7FE001C19F880A96E"
+ "395C42536D694F81B4F44DC66D7D6FBE933C56ABF585837291D8751C18EB1F3FB"
+ "620582E6A7B795D699E38C270863A289583CB9D07651E6BA3B82BC656B49BD09B"
+ "6B8C27F370120C7CB89D0829BE51D56356EA836012E9204FF4D1CA8B1B7F9C768"
+ "4BB2B0F226FD4042EEBAD931FDBD4F81F8425B305752F5E37FFA2B73BB5A034EC"
+ "7EEF5AAC92EA212897E3A2B8961D2147710ECCE127B942AB2",
"05CC4DF005FE006C11111624E14806E4A904A4D1D6A53E795AC7867A960CD4FD");
// x == 0 implies g^x == 1
test("01",
"488759644532FA7C53E5239F2A365D4B9189582BDD2967A1852FE56568382B65"
+ "C66BDFCD9B581EAEF4BB497CAF1290ECDFA47A1D1658DC5DC9248D9A4135"
+ "DC70B6A8497CDF117236841FA18500DC696A92EEF5000ABE68E9C75B37BC"
+ "6A722126BE728163AA90A6B03D5585994D3403557EEF08E819C72D143BBC"
+ "CDF74559645066CB3607E1B0430365356389FC8FB3D66FD2B6E2E834EC23"
+ "0B0234956752D07F983C918488C8E5A124B062D50B44C5E6FB36BCB03E39"
+ "0385B17CF8062B6688371E6AF5915C2B1AAA31C9294943CC6DC1B994FC09"
+ "49CA31828B83F3D6DFB081B26045DFD9F10092588B63F1D6E68881A06522"
+ "5A417CA9555B036DE89D349AC794A43EB28FE320F9A321F06A9364C88B54"
+ "99EEF4816375B119824ACC9AA56D1340B6A49D05F855DE699B351012028C"
+ "CA43001F708CC61E71CA3849935BEEBABC0D268CD41B8D2B8DCA705FDFF8"
+ "1DAA772DA96EDEA0B291FD5C0C1B8EFE5318D37EBC1BFF53A9DDEC4171A6"
+ "479E341438970058E25C8F2BCDA6166C8BF1B065C174",
"8B2BACE575179D762F6F2FFDBFF00B497C07766AB3EED9961447CF6F43D06A97");
}
function test_invalid_input_round2() {
let a = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
.createInstance(Ci.nsISyncJPAKE);
a.round1("alice", {}, {}, {}, {}, {}, {});
do_check_throws(function() {
a.round2("invalid", "sekrit", "some", "real", "garbage",
"even", "more", "garbage", {}, {}, {});
});
}
function test_invalid_input_final() {
let a = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
.createInstance(Ci.nsISyncJPAKE);
let b = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
.createInstance(Ci.nsISyncJPAKE);
let gx1 = {};
let gv1 = {};
let r1 = {};
let gx2 = {};
let gv2 = {};
let r2 = {};
a.round1("alice", {}, {}, {}, {}, {}, {});
b.round1("bob", gx1, gv1, r1, gx2, gv2, r2);
a.round2("bob", "sekrit", gx1.value, gv1.value, r1.value,
gx2.value, gv2.value, r2.value, {}, {}, {});
do_check_throws(function() {
a.final("some", "garbage", "alright", "foobar-info", {}, {});
});
}
function run_test() {
test_x4_zero();
test_success();
test_failure();
test_same_signerids();
test_bad_zkp();
test_invalid_input_round2();
test_invalid_input_final();
}

View File

@ -0,0 +1,5 @@
[DEFAULT]
head =
firefox-appdir = browser
[test_jpake.js]

View File

@ -7,6 +7,8 @@
with Files('**'):
BUG_COMPONENT = ('Mozilla Services', 'Firefox Sync: Crypto')
DIRS += ['component']
XPCSHELL_TESTS_MANIFESTS += ['tests/unit/xpcshell.ini']
EXTRA_JS_MODULES['services-crypto'] += [

View File

@ -36,6 +36,7 @@ const COMMAND_SYNC_PREFERENCES = "fxaccounts:sync_preferences";
const COMMAND_CHANGE_PASSWORD = "fxaccounts:change_password";
const PREF_LAST_FXA_USER = "identity.fxaccounts.lastSignedInUserHash";
const PREF_SYNC_SHOW_CUSTOMIZATION = "services.sync-setup.ui.showCustomizationDialog";
/**
* A helper function that extracts the message and stack from an error object.
@ -250,16 +251,32 @@ this.FxAccountsWebChannelHelpers.prototype = {
this._promptForRelink(acctName);
},
/**
* New users are asked in the content server whether they want to
* customize which data should be synced. The user is only shown
* the dialog listing the possible data types upon verification.
*
* Save a bit into prefs that is read on verification to see whether
* to show the list of data types that can be saved.
*/
setShowCustomizeSyncPref(showCustomizeSyncPref) {
Services.prefs.setBoolPref(PREF_SYNC_SHOW_CUSTOMIZATION, showCustomizeSyncPref);
},
getShowCustomizeSyncPref() {
return Services.prefs.getBoolPref(PREF_SYNC_SHOW_CUSTOMIZATION);
},
/**
* stores sync login info it in the fxaccounts service
*
* @param accountData the user's account data and credentials
*/
login(accountData) {
// We don't act on customizeSync anymore, it used to open a dialog inside
// the browser to selecte the engines to sync but we do it on the web now.
delete accountData.customizeSync;
if (accountData.customizeSync) {
this.setShowCustomizeSyncPref(true);
delete accountData.customizeSync;
}
if (accountData.declinedSyncEngines) {
let declinedSyncEngines = accountData.declinedSyncEngines;
@ -268,6 +285,9 @@ this.FxAccountsWebChannelHelpers.prototype = {
declinedSyncEngines.forEach(engine => {
Services.prefs.setBoolPref("services.sync.engine." + engine, false);
});
// if we got declinedSyncEngines that means we do not need to show the customize screen.
this.setShowCustomizeSyncPref(false);
delete accountData.declinedSyncEngines;
}

View File

@ -5,7 +5,6 @@ var {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;
"use strict";
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
(function initFxAccountsTestingInfrastructure() {

View File

@ -4,6 +4,7 @@
"use strict";
Cu.import("resource://services-common/utils.js");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/FxAccounts.jsm");
Cu.import("resource://gre/modules/FxAccountsClient.jsm");
Cu.import("resource://gre/modules/FxAccountsCommon.js");

View File

@ -4,6 +4,7 @@
"use strict";
Cu.import("resource://services-common/utils.js");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/FxAccounts.jsm");
Cu.import("resource://gre/modules/FxAccountsClient.jsm");
Cu.import("resource://gre/modules/FxAccountsCommon.js");

View File

@ -10,6 +10,7 @@ Services.prefs.setCharPref("identity.fxaccounts.auth.uri", "http://localhost");
// See verbose logging from FxAccounts.jsm
Services.prefs.setCharPref("identity.fxaccounts.loglevel", "Trace");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/FxAccounts.jsm");
Cu.import("resource://gre/modules/FxAccountsClient.jsm");
Cu.import("resource://gre/modules/FxAccountsCommon.js");

View File

@ -5,6 +5,7 @@
Cu.import("resource://gre/modules/FxAccountsCommon.js");
Cu.import("resource://gre/modules/FxAccountsOAuthGrantClient.jsm");
Cu.import("resource://gre/modules/Services.jsm");
const CLIENT_OPTIONS = {
serverURL: "http://127.0.0.1:9010/v1",

View File

@ -6,6 +6,7 @@
// Tests for the FxA push service.
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Promise.jsm");
Cu.import("resource://gre/modules/FxAccountsCommon.js");
Cu.import("resource://gre/modules/Log.jsm");

View File

@ -6,6 +6,7 @@
// Tests for the FxA storage manager.
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/FxAccountsStorage.jsm");
Cu.import("resource://gre/modules/FxAccountsCommon.js");
Cu.import("resource://gre/modules/Log.jsm");

View File

@ -287,6 +287,9 @@ add_task(function* test_helpers_login_without_customize_sync() {
// verifiedCanLinkAccount should be stripped in the data.
do_check_false("verifiedCanLinkAccount" in accountData);
// the customizeSync pref should not update
do_check_false(helpers.getShowCustomizeSyncPref());
// previously signed in user preference is updated.
do_check_eq(helpers.getPreviousAccountNameHashPref(), helpers.sha256("testuser@testuser.com"));
@ -296,6 +299,9 @@ add_task(function* test_helpers_login_without_customize_sync() {
}
});
// the show customize sync pref should stay the same
helpers.setShowCustomizeSyncPref(false);
// ensure the previous account pref is overwritten.
helpers.setPreviousAccountNameHashPref("lastuser@testuser.com");
@ -317,12 +323,18 @@ add_task(function* test_helpers_login_with_customize_sync() {
// customizeSync should be stripped in the data.
do_check_false("customizeSync" in accountData);
// the customizeSync pref should not update
do_check_true(helpers.getShowCustomizeSyncPref());
resolve();
});
}
}
});
// the customize sync pref should be overwritten
helpers.setShowCustomizeSyncPref(false);
yield helpers.login({
email: "testuser@testuser.com",
verifiedCanLinkAccount: true,
@ -348,12 +360,18 @@ add_task(function* test_helpers_login_with_customize_sync_and_declined_engines()
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.prefs"), false);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.tabs"), true);
// the customizeSync pref should be disabled
do_check_false(helpers.getShowCustomizeSyncPref());
resolve();
});
}
}
});
// the customize sync pref should be overwritten
helpers.setShowCustomizeSyncPref(true);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.addons"), true);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.bookmarks"), true);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.history"), true);

View File

@ -72,6 +72,11 @@ WeaveService.prototype = {
Ci.nsISupportsWeakReference]),
ensureLoaded() {
// If we are loaded and not using FxA, load the migration module.
if (!this.fxAccountsEnabled) {
Cu.import("resource://services-sync/FxaMigrator.jsm");
}
Components.utils.import("resource://services-sync/main.js");
// Side-effect of accessing the service is that it is instantiated.
@ -92,10 +97,27 @@ WeaveService.prototype = {
return deferred.promise;
},
/**
* Whether Firefox Accounts is enabled.
*
* @return bool
*/
get fxAccountsEnabled() {
try {
// Old sync guarantees '@' will never appear in the username while FxA
// uses the FxA email address - so '@' is the flag we use.
let username = Services.prefs.getCharPref(SYNC_PREFS_BRANCH + "username");
return !username || username.includes("@");
} catch (_) {
return true; // No username == only allow FxA to be configured.
}
},
/**
* Whether Sync appears to be enabled.
*
* This returns true if we have an associated FxA account
* This returns true if all the Sync preferences for storing account
* and server configuration are populated.
*
* It does *not* perform a robust check to see if the client is working.
* For that, you'll want to check Weave.Status.checkSetup().
@ -120,9 +142,10 @@ WeaveService.prototype = {
notify: function() {
let isConfigured = false;
// We only load more if it looks like Sync is configured.
if (this.enabled) {
// We have an associated FxAccount. So, do a more thorough check.
// This will import a number of modules and thus increase memory
let prefs = Services.prefs.getBranch(SYNC_PREFS_BRANCH);
if (prefs.prefHasUserValue("username")) {
// We have a username. So, do a more thorough check. This will
// import a number of modules and thus increase memory
// accordingly. We could potentially copy code performed by
// this check into this file if our above code is yielding too
// many false positives.

View File

@ -12,5 +12,16 @@ lastSync2.label = Last sync: %S
# not configured.
signInToSync.description = Sign In To Sync
error.sync.title = Error While Syncing
error.sync.description = Sync encountered an error while syncing: %1$S. Sync will automatically retry this action.
warning.sync.eol.label = Service Shutting Down
# %1: the app name (Firefox)
warning.sync.eol.description = Your Firefox Sync service is shutting down soon. Upgrade %1$S to keep syncing.
error.sync.eol.label = Service Unavailable
# %1: the app name (Firefox)
error.sync.eol.description = Your Firefox Sync service is no longer available. You need to upgrade %1$S to keep syncing.
sync.eol.learnMore.label = Learn more
sync.eol.learnMore.accesskey = L
syncnow.label = Sync Now
syncing2.label = Syncing…

View File

@ -7,6 +7,9 @@
this.EXPORTED_SYMBOLS = [
"btoa", // It comes from a module import.
"encryptPayload",
"isConfiguredWithLegacyIdentity",
"ensureLegacyIdentityManager",
"setBasicCredentials",
"makeIdentityConfig",
"makeFxAccountsInternalMock",
"configureFxAccountIdentity",
@ -15,6 +18,7 @@ this.EXPORTED_SYMBOLS = [
"waitForZeroTimer",
"promiseZeroTimer",
"promiseNamedTimer",
"add_identity_test",
"MockFxaStorageManager",
"AccountState", // from a module import
"sumHistogram",
@ -23,6 +27,7 @@ this.EXPORTED_SYMBOLS = [
var {utils: Cu} = Components;
Cu.import("resource://services-sync/status.js");
Cu.import("resource://services-sync/identity.js");
Cu.import("resource://services-common/utils.js");
Cu.import("resource://services-crypto/utils.js");
Cu.import("resource://services-sync/util.js");
@ -103,6 +108,40 @@ this.promiseNamedTimer = function(wait, thisObj, name) {
});
}
/**
* Return true if Sync is configured with the "legacy" identity provider.
*/
this.isConfiguredWithLegacyIdentity = function() {
let ns = {};
Cu.import("resource://services-sync/service.js", ns);
// We can't use instanceof as BrowserIDManager (the "other" identity) inherits
// from IdentityManager so that would return true - so check the prototype.
return Object.getPrototypeOf(ns.Service.identity) === IdentityManager.prototype;
}
/**
* Ensure Sync is configured with the "legacy" identity provider.
*/
this.ensureLegacyIdentityManager = function() {
let ns = {};
Cu.import("resource://services-sync/service.js", ns);
Status.__authManager = ns.Service.identity = new IdentityManager();
ns.Service._clusterManager = ns.Service.identity.createClusterManager(ns.Service);
}
this.setBasicCredentials =
function setBasicCredentials(username, password, syncKey) {
let ns = {};
Cu.import("resource://services-sync/service.js", ns);
let auth = ns.Service.identity;
auth.username = username;
auth.basicPassword = password;
auth.syncKey = syncKey;
}
// Return an identity configuration suitable for testing with our identity
// providers. |overrides| can specify overrides for any default values.
// |server| is optional, but if specified, will be used to form the cluster
@ -131,6 +170,11 @@ this.makeIdentityConfig = function(overrides) {
hashed_fxa_uid: "f".repeat(32), // used during telemetry validation
// uid will be set to the username.
}
},
sync: {
// username will come from the top-level username
password: "whatever",
syncKey: "abcdeabcdeabcdeabcdeabcdea",
}
};
@ -139,6 +183,10 @@ this.makeIdentityConfig = function(overrides) {
if (overrides.username) {
result.username = overrides.username;
}
if (overrides.sync) {
// TODO: allow just some attributes to be specified
result.sync = overrides.sync;
}
if (overrides.fxaccount) {
// TODO: allow just some attributes to be specified
result.fxaccount = overrides.fxaccount;
@ -208,30 +256,48 @@ this.configureIdentity = async function(identityOverrides, server) {
let ns = {};
Cu.import("resource://services-sync/service.js", ns);
// If a server was specified, ensure FxA has a correct cluster URL available.
if (server && !config.fxaccount.token.endpoint) {
let ep = server.baseURI;
if (!ep.endsWith("/")) {
ep += "/";
}
ep += "1.1/" + config.username + "/";
config.fxaccount.token.endpoint = ep;
if (server) {
ns.Service.serverURL = server.baseURI;
}
configureFxAccountIdentity(ns.Service.identity, config);
await ns.Service.identity.initializeWithCurrentIdentity();
// and cheat to avoid requiring each test do an explicit login - give it
// a cluster URL.
if (config.fxaccount.token.endpoint) {
ns.Service.clusterURL = config.fxaccount.token.endpoint;
ns.Service._clusterManager = ns.Service.identity.createClusterManager(ns.Service);
if (ns.Service.identity instanceof BrowserIDManager) {
// do the FxAccounts thang...
// If a server was specified, ensure FxA has a correct cluster URL available.
if (server && !config.fxaccount.token.endpoint) {
let ep = server.baseURI;
if (!ep.endsWith("/")) {
ep += "/";
}
ep += "1.1/" + config.username + "/";
config.fxaccount.token.endpoint = ep;
}
configureFxAccountIdentity(ns.Service.identity, config);
await ns.Service.identity.initializeWithCurrentIdentity();
// and cheat to avoid requiring each test do an explicit login - give it
// a cluster URL.
if (config.fxaccount.token.endpoint) {
ns.Service.clusterURL = config.fxaccount.token.endpoint;
}
return;
}
// old style identity provider.
if (server) {
ns.Service.clusterURL = server.baseURI + "/";
}
ns.Service.identity.username = config.username;
ns.Service._updateCachedURLs();
setBasicCredentials(config.username, config.sync.password, config.sync.syncKey);
}
this.SyncTestingInfrastructure = async function(server, username) {
this.SyncTestingInfrastructure = async function(server, username, password) {
let ns = {};
Cu.import("resource://services-sync/service.js", ns);
let config = makeIdentityConfig({ username });
let config = makeIdentityConfig({ username, password });
await configureIdentity(config, server);
return {
logStats: initTestLogging(),
@ -256,6 +322,41 @@ this.encryptPayload = function encryptPayload(cleartext) {
};
}
// This helper can be used instead of 'add_test' or 'add_task' to run the
// specified test function twice - once with the old-style sync identity
// manager and once with the new-style BrowserID identity manager, to ensure
// it works in both cases.
//
// * The test itself should be passed as 'test' - ie, test code will generally
// pass |this|.
// * The test function is a regular test function - although note that it must
// be a generator - async operations should yield them, and run_next_test
// mustn't be called.
this.add_identity_test = function(test, testFunction) {
function note(what) {
let msg = "running test " + testFunction.name + " with " + what + " identity manager";
test.do_print(msg);
}
let ns = {};
Cu.import("resource://services-sync/service.js", ns);
// one task for the "old" identity manager.
test.add_task(async function() {
note("sync");
let oldIdentity = Status._authManager;
ensureLegacyIdentityManager();
await testFunction();
Status.__authManager = ns.Service.identity = oldIdentity;
});
// another task for the FxAccounts identity manager.
test.add_task(async function() {
note("FxAccounts");
let oldIdentity = Status._authManager;
Status.__authManager = ns.Service.identity = new BrowserIDManager();
await testFunction();
Status.__authManager = ns.Service.identity = oldIdentity;
});
}
this.sumHistogram = function(name, options = {}) {
let histogram = options.key ? Services.telemetry.getKeyedHistogramById(name) :
Services.telemetry.getHistogramById(name);

View File

@ -0,0 +1,99 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict;"
// Note that this module used to supervise the step-by-step migration from
// a legacy Sync account to a FxA-based Sync account. In bug 1205928, this
// changed to automatically disconnect the legacy Sync account.
const {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyGetter(this, "WeaveService", function() {
return Cc["@mozilla.org/weave/service;1"]
.getService(Components.interfaces.nsISupports)
.wrappedJSObject;
});
XPCOMUtils.defineLazyModuleGetter(this, "Weave",
"resource://services-sync/main.js");
// We send this notification when we perform the disconnection. The browser
// window will show a one-off notification bar.
const OBSERVER_STATE_CHANGE_TOPIC = "fxa-migration:state-changed";
const OBSERVER_TOPICS = [
"xpcom-shutdown",
"weave:eol",
];
function Migrator() {
// Leave the log-level as Debug - Sync will setup log appenders such that
// these messages generally will not be seen unless other log related
// prefs are set.
this.log.level = Log.Level.Debug;
for (let topic of OBSERVER_TOPICS) {
Services.obs.addObserver(this, topic, false);
}
}
Migrator.prototype = {
log: Log.repository.getLogger("Sync.SyncMigration"),
finalize() {
for (let topic of OBSERVER_TOPICS) {
Services.obs.removeObserver(this, topic);
}
},
observe(subject, topic, data) {
this.log.debug("observed " + topic);
switch (topic) {
case "xpcom-shutdown":
this.finalize();
break;
default:
// this notification when configured with legacy Sync means we want to
// disconnect
if (!WeaveService.fxAccountsEnabled) {
this.log.info("Disconnecting from legacy Sync");
// Set up an observer for when the disconnection is complete.
let observe;
Services.obs.addObserver(observe = () => {
this.log.info("observed that startOver is complete");
Services.obs.removeObserver(observe, "weave:service:start-over:finish");
// Send the notification for the UI.
Services.obs.notifyObservers(null, OBSERVER_STATE_CHANGE_TOPIC, null);
}, "weave:service:start-over:finish", false);
// Do the disconnection.
Weave.Service.startOver();
}
}
},
get learnMoreLink() {
try {
var url = Services.prefs.getCharPref("app.support.baseURL");
} catch (err) {
return null;
}
url += "sync-upgrade";
let sb = Services.strings.createBundle("chrome://weave/locale/services/sync.properties");
return {
text: sb.GetStringFromName("sync.eol.learnMore.label"),
href: Services.urlFormatter.formatURL(url),
};
},
};
// We expose a singleton
this.EXPORTED_SYMBOLS = ["fxaMigrator"];
var fxaMigrator = new Migrator();

View File

@ -13,11 +13,13 @@ Cu.import("resource://services-common/async.js");
Cu.import("resource://services-common/utils.js");
Cu.import("resource://services-common/tokenserverclient.js");
Cu.import("resource://services-crypto/utils.js");
Cu.import("resource://services-sync/identity.js");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://services-common/tokenserverclient.js");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://services-sync/constants.js");
Cu.import("resource://gre/modules/Promise.jsm");
Cu.import("resource://services-sync/stages/cluster.js");
Cu.import("resource://gre/modules/FxAccounts.jsm");
// Lazy imports to prevent unnecessary load on startup.
@ -46,6 +48,8 @@ const OBSERVER_TOPICS = [
fxAccountsCommon.ON_ACCOUNT_STATE_CHANGE_NOTIFICATION,
];
const PREF_SYNC_SHOW_CUSTOMIZATION = "services.sync-setup.ui.showCustomizationDialog";
function deriveKeyBundle(kB) {
let out = CryptoUtils.hkdf(kB, undefined,
"identity.mozilla.com/picl/v1/oldsync", 2 * 32);
@ -85,6 +89,8 @@ this.BrowserIDManager = function BrowserIDManager() {
};
this.BrowserIDManager.prototype = {
__proto__: IdentityManager.prototype,
_fxaService: null,
_tokenServerClient: null,
// https://docs.services.mozilla.com/token/apis.html
@ -100,6 +106,14 @@ this.BrowserIDManager.prototype = {
// we don't consider the lack of a keybundle as a failure state.
_shouldHaveSyncKeyBundle: false,
get needsCustomization() {
try {
return Services.prefs.getBoolPref(PREF_SYNC_SHOW_CUSTOMIZATION);
} catch (e) {
return false;
}
},
hashedUID() {
if (!this._hashedUID) {
throw new Error("hashedUID: Don't seem to have previously seen a token");
@ -124,6 +138,19 @@ this.BrowserIDManager.prototype = {
for (let topic of OBSERVER_TOPICS) {
Services.obs.addObserver(this, topic, false);
}
// and a background fetch of account data just so we can set this.account,
// so we have a username available before we've actually done a login.
// XXX - this is actually a hack just for tests and really shouldn't be
// necessary. Also, you'd think it would be safe to allow this.account to
// be set to null when there's no user logged in, but argue with the test
// suite, not with me :)
this._fxaService.getSignedInUser().then(accountData => {
if (accountData) {
this.account = accountData.email;
}
}).catch(err => {
// As above, this is only for tests so it is safe to ignore.
});
},
/**
@ -163,6 +190,19 @@ this.BrowserIDManager.prototype = {
this._signedInUser = null;
},
offerSyncOptions() {
// If the user chose to "Customize sync options" when signing
// up with Firefox Accounts, ask them to choose what to sync.
const url = "chrome://browser/content/sync/customize.xul";
const features = "centerscreen,chrome,modal,dialog,resizable=no";
let win = Services.wm.getMostRecentWindow("navigator:browser");
let data = {accepted: false};
win.openDialog(url, "_blank", features, data);
return data;
},
initializeWithCurrentIdentity(isInitialSync = false) {
// While this function returns a promise that resolves once we've started
// the auth process, that process is complete when
@ -185,13 +225,14 @@ this.BrowserIDManager.prototype = {
return this._fxaService.getSignedInUser().then(accountData => {
if (!accountData) {
this._log.info("initializeWithCurrentIdentity has no user logged in");
this.account = null;
// and we are as ready as we can ever be for auth.
this._shouldHaveSyncKeyBundle = true;
this.whenReadyToAuthenticate.reject("no user is logged in");
return;
}
this.username = accountData.email;
this.account = accountData.email;
this._updateSignedInUser(accountData);
// The user must be verified before we can do anything at all; we kick
// this and the rest of initialization off in the background (ie, we
@ -199,8 +240,20 @@ this.BrowserIDManager.prototype = {
this._log.info("Waiting for user to be verified.");
this._fxaService.whenVerified(accountData).then(accountData => {
this._updateSignedInUser(accountData);
this._log.info("Starting fetch for key bundle.");
if (this.needsCustomization) {
let data = this.offerSyncOptions();
if (data.accepted) {
Services.prefs.clearUserPref(PREF_SYNC_SHOW_CUSTOMIZATION);
// Mark any non-selected engines as declined.
Weave.Service.engineManager.declineDisabled();
} else {
// Log out if the user canceled the dialog.
return this._fxaService.signOut();
}
}
}).then(() => {
return this._fetchTokenForUser();
}).then(token => {
this._token = token;
@ -312,43 +365,65 @@ this.BrowserIDManager.prototype = {
return this._fxaService.localtimeOffsetMsec;
},
get syncKeyBundle() {
return this._syncKeyBundle;
},
get username() {
return Svc.Prefs.get("username", null);
usernameFromAccount(val) {
// we don't differentiate between "username" and "account"
return val;
},
/**
* Set the username value.
* Obtains the HTTP Basic auth password.
*
* Changing the username has the side-effect of wiping credentials.
* Returns a string if set or null if it is not set.
*/
set username(value) {
if (value) {
value = value.toLowerCase();
get basicPassword() {
this._log.error("basicPassword getter should be not used in BrowserIDManager");
return null;
},
if (value == this.username) {
return;
}
/**
* Set the HTTP basic password to use.
*
* Changes will not persist unless persistSyncCredentials() is called.
*/
set basicPassword(value) {
throw new Error("basicPassword setter should be not used in BrowserIDManager");
},
Svc.Prefs.set("username", value);
} else {
Svc.Prefs.reset("username");
/**
* Obtain the Sync Key.
*
* This returns a 26 character "friendly" Base32 encoded string on success or
* null if no Sync Key could be found.
*
* If the Sync Key hasn't been set in this session, this will look in the
* password manager for the sync key.
*/
get syncKey() {
if (this.syncKeyBundle) {
// TODO: This is probably fine because the code shouldn't be
// using the sync key directly (it should use the sync key
// bundle), but I don't like it. We should probably refactor
// code that is inspecting this to not do validation on this
// field directly and instead call a isSyncKeyValid() function
// that we can override.
return "99999999999999999999999999";
}
return null;
},
// If we change the username, we interpret this as a major change event
// and wipe out the credentials.
this._log.info("Username changed. Removing stored credentials.");
this.resetCredentials();
set syncKey(value) {
throw "syncKey setter should be not used in BrowserIDManager";
},
get syncKeyBundle() {
return this._syncKeyBundle;
},
/**
* Resets/Drops all credentials we hold for the current user.
*/
resetCredentials() {
this.resetSyncKeyBundle();
this.resetSyncKey();
this._token = null;
this._hashedUID = null;
// The cluster URL comes from the token, so resetting it to empty will
@ -357,10 +432,12 @@ this.BrowserIDManager.prototype = {
},
/**
* Resets/Drops the sync key bundle we hold for the current user.
* Resets/Drops the sync key we hold for the current user.
*/
resetSyncKeyBundle() {
resetSyncKey() {
this._syncKey = null;
this._syncKeyBundle = null;
this._syncKeyUpdated = true;
this._shouldHaveSyncKeyBundle = false;
},
@ -381,18 +458,6 @@ this.BrowserIDManager.prototype = {
return Utils.getSyncCredentialsHostsFxA();
},
/**
* Deletes Sync credentials from the password manager.
*/
deleteSyncCredentials() {
for (let host of this._getSyncCredentialsHosts()) {
let logins = Services.logins.findLogins({}, host, "", "");
for (let login of logins) {
Services.logins.removeLogin(login);
}
}
},
/**
* The current state of the auth credentials.
*
@ -407,7 +472,6 @@ this.BrowserIDManager.prototype = {
" due to previous failure");
return this._authFailureReason;
}
// TODO: need to revisit this. Currently this isn't ready to go until
// both the username and syncKeyBundle are both configured and having no
// username seems to make things fail fast so that's good.
@ -737,39 +801,11 @@ this.BrowserIDManager.prototype = {
*/
function BrowserIDClusterManager(service) {
this._log = log;
this.service = service;
ClusterManager.call(this, service);
}
BrowserIDClusterManager.prototype = {
get identity() {
return this.service.identity;
},
/**
* Determine the cluster for the current user and update state.
*/
setCluster() {
// Make sure we didn't get some unexpected response for the cluster.
let cluster = this._findCluster();
this._log.debug("Cluster value = " + cluster);
if (cluster == null) {
return false;
}
// Convert from the funky "String object with additional properties" that
// resource.js returns to a plain-old string.
cluster = cluster.toString();
// Don't update stuff if we already have the right cluster
if (cluster == this.service.clusterURL) {
return false;
}
this._log.debug("Setting cluster to " + cluster);
this.service.clusterURL = cluster;
return true;
},
__proto__: ClusterManager.prototype,
_findCluster() {
let endPointFromIdentityToken = function() {

View File

@ -11,6 +11,8 @@ WEAVE_VERSION: "@weave_version@",
// Sync Server API version that the client supports.
SYNC_API_VERSION: "1.1",
USER_API_VERSION: "1.0",
MISC_API_VERSION: "1.0",
// Version of the data format this client supports. The data format describes
// how records are packaged; this is separate from the Server API version and
@ -122,6 +124,7 @@ ENGINE_SUCCEEDED: "success.engine",
// login failure status codes:
LOGIN_FAILED_NO_USERNAME: "error.login.reason.no_username",
LOGIN_FAILED_NO_PASSWORD: "error.login.reason.no_password2",
LOGIN_FAILED_NO_PASSPHRASE: "error.login.reason.no_recoverykey",
LOGIN_FAILED_NETWORK_ERROR: "error.login.reason.network",
LOGIN_FAILED_SERVER_ERROR: "error.login.reason.server",
@ -152,6 +155,18 @@ ENGINE_METARECORD_UPLOAD_FAIL: "error.engine.reason.metarecord_upload_fa
// an upload failure where the batch was interrupted with a 412
ENGINE_BATCH_INTERRUPTED: "error.engine.reason.batch_interrupted",
JPAKE_ERROR_CHANNEL: "jpake.error.channel",
JPAKE_ERROR_NETWORK: "jpake.error.network",
JPAKE_ERROR_SERVER: "jpake.error.server",
JPAKE_ERROR_TIMEOUT: "jpake.error.timeout",
JPAKE_ERROR_INTERNAL: "jpake.error.internal",
JPAKE_ERROR_INVALID: "jpake.error.invalid",
JPAKE_ERROR_NODATA: "jpake.error.nodata",
JPAKE_ERROR_KEYMISMATCH: "jpake.error.keymismatch",
JPAKE_ERROR_WRONGMESSAGE: "jpake.error.wrongmessage",
JPAKE_ERROR_USERABORT: "jpake.error.userabort",
JPAKE_ERROR_DELAYUNSUPPORTED: "jpake.error.delayunsupported",
// info types for Service.getStorageInfo
INFO_COLLECTIONS: "collections",
INFO_COLLECTION_USAGE: "collection_usage",

View File

@ -19,6 +19,7 @@ Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://gre/modules/osfile.jsm");
Cu.import("resource://services-common/observers.js");
Cu.import("resource://services-sync/constants.js");
Cu.import("resource://services-sync/identity.js");
Cu.import("resource://services-sync/record.js");
Cu.import("resource://services-sync/resource.js");
Cu.import("resource://services-sync/util.js");

View File

@ -0,0 +1,604 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
this.EXPORTED_SYMBOLS = ["IdentityManager"];
var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Promise.jsm");
Cu.import("resource://services-sync/constants.js");
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://services-common/async.js");
// Lazy import to prevent unnecessary load on startup.
for (let symbol of ["BulkKeyBundle", "SyncKeyBundle"]) {
XPCOMUtils.defineLazyModuleGetter(this, symbol,
"resource://services-sync/keys.js",
symbol);
}
/**
* Manages "legacy" identity and authentication for Sync.
* See browserid_identity for the Firefox Accounts based identity manager.
*
* The following entities are managed:
*
* account - The main Sync/services account. This is typically an email
* address.
* username - A normalized version of your account. This is what's
* transmitted to the server.
* basic password - UTF-8 password used for authenticating when using HTTP
* basic authentication.
* sync key - The main encryption key used by Sync.
* sync key bundle - A representation of your sync key.
*
* When changes are made to entities that are stored in the password manager
* (basic password, sync key), those changes are merely staged. To commit them
* to the password manager, you'll need to call persistCredentials().
*
* This type also manages authenticating Sync's network requests. Sync's
* network code calls into getRESTRequestAuthenticator and
* getResourceAuthenticator (depending on the network layer being used). Each
* returns a function which can be used to add authentication information to an
* outgoing request.
*
* In theory, this type supports arbitrary identity and authentication
* mechanisms. You can add support for them by monkeypatching the global
* instance of this type. Specifically, you'll need to redefine the
* aforementioned network code functions to do whatever your authentication
* mechanism needs them to do. In addition, you may wish to install custom
* functions to support your API. Although, that is certainly not required.
* If you do monkeypatch, please be advised that Sync expects the core
* attributes to have values. You will need to carry at least account and
* username forward. If you do not wish to support one of the built-in
* authentication mechanisms, you'll probably want to redefine currentAuthState
* and any other function that involves the built-in functionality.
*/
this.IdentityManager = function IdentityManager() {
this._log = Log.repository.getLogger("Sync.Identity");
this._log.Level = Log.Level[Svc.Prefs.get("log.logger.identity")];
this._basicPassword = null;
this._basicPasswordAllowLookup = true;
this._basicPasswordUpdated = false;
this._syncKey = null;
this._syncKeyAllowLookup = true;
this._syncKeySet = false;
this._syncKeyBundle = null;
}
IdentityManager.prototype = {
_log: null,
_basicPassword: null,
_basicPasswordAllowLookup: true,
_basicPasswordUpdated: false,
_syncKey: null,
_syncKeyAllowLookup: true,
_syncKeySet: false,
_syncKeyBundle: null,
/**
* Initialize the identity provider.
*/
initialize() {
// Nothing to do for this identity provider.
},
finalize() {
// Nothing to do for this identity provider.
},
/**
* Called whenever Service.logout() is called.
*/
logout() {
// nothing to do for this identity provider.
},
/**
* Ensure the user is logged in. Returns a promise that resolves when
* the user is logged in, or is rejected if the login attempt has failed.
*/
ensureLoggedIn() {
// nothing to do for this identity provider
return Promise.resolve();
},
get account() {
return Svc.Prefs.get("account", this.username);
},
/**
* Sets the active account name.
*
* This should almost always be called in favor of setting username, as
* username is derived from account.
*
* Changing the account name has the side-effect of wiping out stored
* credentials. Keep in mind that persistCredentials() will need to be called
* to flush the changes to disk.
*
* Set this value to null to clear out identity information.
*/
set account(value) {
if (value) {
value = value.toLowerCase();
Svc.Prefs.set("account", value);
} else {
Svc.Prefs.reset("account");
}
this.username = this.usernameFromAccount(value);
},
get username() {
return Svc.Prefs.get("username", null);
},
/**
* Set the username value.
*
* Changing the username has the side-effect of wiping credentials.
*/
set username(value) {
if (value) {
value = value.toLowerCase();
if (value == this.username) {
return;
}
Svc.Prefs.set("username", value);
} else {
Svc.Prefs.reset("username");
}
// If we change the username, we interpret this as a major change event
// and wipe out the credentials.
this._log.info("Username changed. Removing stored credentials.");
this.resetCredentials();
},
/**
* Resets/Drops all credentials we hold for the current user.
*/
resetCredentials() {
this.basicPassword = null;
this.resetSyncKey();
},
/**
* Resets/Drops the sync key we hold for the current user.
*/
resetSyncKey() {
this.syncKey = null;
// syncKeyBundle cleared as a result of setting syncKey.
},
/**
* Obtains the HTTP Basic auth password.
*
* Returns a string if set or null if it is not set.
*/
get basicPassword() {
if (this._basicPasswordAllowLookup) {
// We need a username to find the credentials.
let username = this.username;
if (!username) {
return null;
}
for (let login of this._getLogins(PWDMGR_PASSWORD_REALM)) {
if (login.username.toLowerCase() == username) {
// It should already be UTF-8 encoded, but we don't take any chances.
this._basicPassword = Utils.encodeUTF8(login.password);
}
}
this._basicPasswordAllowLookup = false;
}
return this._basicPassword;
},
/**
* Set the HTTP basic password to use.
*
* Changes will not persist unless persistSyncCredentials() is called.
*/
set basicPassword(value) {
// Wiping out value.
if (!value) {
this._log.info("Basic password has no value. Removing.");
this._basicPassword = null;
this._basicPasswordUpdated = true;
this._basicPasswordAllowLookup = false;
return;
}
let username = this.username;
if (!username) {
throw new Error("basicPassword cannot be set before username.");
}
this._log.info("Basic password being updated.");
this._basicPassword = Utils.encodeUTF8(value);
this._basicPasswordUpdated = true;
},
/**
* Obtain the Sync Key.
*
* This returns a 26 character "friendly" Base32 encoded string on success or
* null if no Sync Key could be found.
*
* If the Sync Key hasn't been set in this session, this will look in the
* password manager for the sync key.
*/
get syncKey() {
if (this._syncKeyAllowLookup) {
let username = this.username;
if (!username) {
return null;
}
for (let login of this._getLogins(PWDMGR_PASSPHRASE_REALM)) {
if (login.username.toLowerCase() == username) {
this._syncKey = login.password;
}
}
this._syncKeyAllowLookup = false;
}
return this._syncKey;
},
/**
* Set the active Sync Key.
*
* If being set to null, the Sync Key and its derived SyncKeyBundle are
* removed. However, the Sync Key won't be deleted from the password manager
* until persistSyncCredentials() is called.
*
* If a value is provided, it should be a 26 or 32 character "friendly"
* Base32 string for which Utils.isPassphrase() returns true.
*
* A side-effect of setting the Sync Key is that a SyncKeyBundle is
* generated. For historical reasons, this will silently error out if the
* value is not a proper Sync Key (!Utils.isPassphrase()). This should be
* fixed in the future (once service.js is more sane) to throw if the passed
* value is not valid.
*/
set syncKey(value) {
if (!value) {
this._log.info("Sync Key has no value. Deleting.");
this._syncKey = null;
this._syncKeyBundle = null;
this._syncKeyUpdated = true;
return;
}
if (!this.username) {
throw new Error("syncKey cannot be set before username.");
}
this._log.info("Sync Key being updated.");
this._syncKey = value;
// Clear any cached Sync Key Bundle and regenerate it.
this._syncKeyBundle = null;
this._syncKeyUpdated = true;
},
/**
* Obtain the active SyncKeyBundle.
*
* This returns a SyncKeyBundle representing a key pair derived from the
* Sync Key on success. If no Sync Key is present or if the Sync Key is not
* valid, this returns null.
*
* The SyncKeyBundle should be treated as immutable.
*/
get syncKeyBundle() {
// We can't obtain a bundle without a username set.
if (!this.username) {
this._log.warn("Attempted to obtain Sync Key Bundle with no username set!");
return null;
}
if (!this.syncKey) {
this._log.warn("Attempted to obtain Sync Key Bundle with no Sync Key " +
"set!");
return null;
}
if (!this._syncKeyBundle) {
try {
this._syncKeyBundle = new SyncKeyBundle(this.username, this.syncKey);
} catch (ex) {
this._log.warn("Failed to create sync bundle", ex);
return null;
}
}
return this._syncKeyBundle;
},
/**
* The current state of the auth credentials.
*
* This essentially validates that enough credentials are available to use
* Sync.
*/
get currentAuthState() {
if (!this.username) {
return LOGIN_FAILED_NO_USERNAME;
}
if (Utils.mpLocked()) {
return STATUS_OK;
}
if (!this.basicPassword) {
return LOGIN_FAILED_NO_PASSWORD;
}
if (!this.syncKey) {
return LOGIN_FAILED_NO_PASSPHRASE;
}
// If we have a Sync Key but no bundle, bundle creation failed, which
// implies a bad Sync Key.
if (!this.syncKeyBundle) {
return LOGIN_FAILED_INVALID_PASSPHRASE;
}
return STATUS_OK;
},
/**
* Verify the current auth state, unlocking the master-password if necessary.
*
* Returns a promise that resolves with the current auth state after
* attempting to unlock.
*/
unlockAndVerifyAuthState() {
// Try to fetch the passphrase - this will prompt for MP unlock as a
// side-effect...
try {
this.syncKey;
} catch (ex) {
this._log.debug("Fetching passphrase threw " + ex +
"; assuming master password locked.");
return Promise.resolve(MASTER_PASSWORD_LOCKED);
}
return Promise.resolve(STATUS_OK);
},
/**
* Persist credentials to password store.
*
* When credentials are updated, they are changed in memory only. This will
* need to be called to save them to the underlying password store.
*
* If the password store is locked (e.g. if the master password hasn't been
* entered), this could throw an exception.
*/
persistCredentials: function persistCredentials(force) {
if (this._basicPasswordUpdated || force) {
if (this._basicPassword) {
this._setLogin(PWDMGR_PASSWORD_REALM, this.username,
this._basicPassword);
} else {
for (let login of this._getLogins(PWDMGR_PASSWORD_REALM)) {
Services.logins.removeLogin(login);
}
}
this._basicPasswordUpdated = false;
}
if (this._syncKeyUpdated || force) {
if (this._syncKey) {
this._setLogin(PWDMGR_PASSPHRASE_REALM, this.username, this._syncKey);
} else {
for (let login of this._getLogins(PWDMGR_PASSPHRASE_REALM)) {
Services.logins.removeLogin(login);
}
}
this._syncKeyUpdated = false;
}
},
/**
* Deletes the Sync Key from the system.
*/
deleteSyncKey: function deleteSyncKey() {
this.syncKey = null;
this.persistCredentials();
},
hasBasicCredentials: function hasBasicCredentials() {
// Because JavaScript.
return this.username && this.basicPassword && true;
},
/**
* Pre-fetches any information that might help with migration away from this
* identity. Called after every sync and is really just an optimization that
* allows us to avoid a network request for when we actually need the
* migration info.
*/
prefetchMigrationSentinel(service) {
// Try and fetch the migration sentinel - it will end up in the recordManager
// cache.
try {
service.recordManager.get(service.storageURL + "meta/fxa_credentials");
} catch (ex) {
if (Async.isShutdownException(ex)) {
throw ex;
}
this._log.warn("Failed to pre-fetch the migration sentinel", ex);
}
},
/**
* Obtains the array of basic logins from nsiPasswordManager.
*/
_getLogins: function _getLogins(realm) {
return Services.logins.findLogins({}, PWDMGR_HOST, null, realm);
},
/**
* Set a login in the password manager.
*
* This has the side-effect of deleting any other logins for the specified
* realm.
*/
_setLogin: function _setLogin(realm, username, password) {
let exists = false;
for (let login of this._getLogins(realm)) {
if (login.username == username && login.password == password) {
exists = true;
} else {
this._log.debug("Pruning old login for " + username + " from " + realm);
Services.logins.removeLogin(login);
}
}
if (exists) {
return;
}
this._log.debug("Updating saved password for " + username + " in " +
realm);
let loginInfo = new Components.Constructor(
"@mozilla.org/login-manager/loginInfo;1", Ci.nsILoginInfo, "init");
let login = new loginInfo(PWDMGR_HOST, null, realm, username,
password, "", "");
Services.logins.addLogin(login);
},
/**
* Return credentials hosts for this identity only.
*/
_getSyncCredentialsHosts() {
return Utils.getSyncCredentialsHostsLegacy();
},
/**
* Deletes Sync credentials from the password manager.
*/
deleteSyncCredentials: function deleteSyncCredentials() {
for (let host of this._getSyncCredentialsHosts()) {
let logins = Services.logins.findLogins({}, host, "", "");
for (let login of logins) {
Services.logins.removeLogin(login);
}
}
// Wait until after store is updated in case it fails.
this._basicPassword = null;
this._basicPasswordAllowLookup = true;
this._basicPasswordUpdated = false;
this._syncKey = null;
// this._syncKeyBundle is nullified as part of _syncKey setter.
this._syncKeyAllowLookup = true;
this._syncKeyUpdated = false;
},
usernameFromAccount: function usernameFromAccount(value) {
// If we encounter characters not allowed by the API (as found for
// instance in an email address), hash the value.
if (value && value.match(/[^A-Z0-9._-]/i)) {
return Utils.sha1Base32(value.toLowerCase()).toLowerCase();
}
return value ? value.toLowerCase() : value;
},
/**
* Obtain a function to be used for adding auth to Resource HTTP requests.
*/
getResourceAuthenticator: function getResourceAuthenticator() {
if (this.hasBasicCredentials()) {
return this._onResourceRequestBasic.bind(this);
}
return null;
},
/**
* Helper method to return an authenticator for basic Resource requests.
*/
getBasicResourceAuthenticator:
function getBasicResourceAuthenticator(username, password) {
return function basicAuthenticator(resource) {
let value = "Basic " + btoa(username + ":" + password);
return {headers: {authorization: value}};
};
},
_onResourceRequestBasic: function _onResourceRequestBasic(resource) {
let value = "Basic " + btoa(this.username + ":" + this.basicPassword);
return {headers: {authorization: value}};
},
_onResourceRequestMAC: function _onResourceRequestMAC(resource, method) {
// TODO Get identifier and key from somewhere.
let identifier;
let key;
let result = Utils.computeHTTPMACSHA1(identifier, key, method, resource.uri);
return {headers: {authorization: result.header}};
},
/**
* Obtain a function to be used for adding auth to RESTRequest instances.
*/
getRESTRequestAuthenticator: function getRESTRequestAuthenticator() {
if (this.hasBasicCredentials()) {
return this.onRESTRequestBasic.bind(this);
}
return null;
},
onRESTRequestBasic: function onRESTRequestBasic(request) {
let up = this.username + ":" + this.basicPassword;
request.setHeader("authorization", "Basic " + btoa(up));
},
createClusterManager(service) {
Cu.import("resource://services-sync/stages/cluster.js");
return new ClusterManager(service);
},
offerSyncOptions() {
// Do nothing for Sync 1.1.
return {accepted: true};
},
// Tell Sync what the login status should be if it saw a 401 fetching
// info/collections as part of login verification (typically immediately
// after login.)
// In our case it means an authoritative "password is incorrect".
loginStatusFromVerification404() {
return LOGIN_FAILED_LOGIN_REJECTED;
}
};

View File

@ -0,0 +1,773 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
this.EXPORTED_SYMBOLS = ["JPAKEClient", "SendCredentialsController"];
var {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://services-common/rest.js");
Cu.import("resource://services-sync/constants.js");
Cu.import("resource://services-sync/util.js");
const REQUEST_TIMEOUT = 60; // 1 minute
const KEYEXCHANGE_VERSION = 3;
const JPAKE_SIGNERID_SENDER = "sender";
const JPAKE_SIGNERID_RECEIVER = "receiver";
const JPAKE_LENGTH_SECRET = 8;
const JPAKE_LENGTH_CLIENTID = 256;
const JPAKE_VERIFY_VALUE = "0123456789ABCDEF";
/**
* Client to exchange encrypted data using the J-PAKE algorithm.
* The exchange between two clients of this type looks like this:
*
*
* Mobile Server Desktop
* ===================================================================
* |
* retrieve channel <---------------|
* generate random secret |
* show PIN = secret + channel | ask user for PIN
* upload Mobile's message 1 ------>|
* |----> retrieve Mobile's message 1
* |<----- upload Desktop's message 1
* retrieve Desktop's message 1 <---|
* upload Mobile's message 2 ------>|
* |----> retrieve Mobile's message 2
* | compute key
* |<----- upload Desktop's message 2
* retrieve Desktop's message 2 <---|
* compute key |
* encrypt known value ------------>|
* |-------> retrieve encrypted value
* | verify against local known value
*
* At this point Desktop knows whether the PIN was entered correctly.
* If it wasn't, Desktop deletes the session. If it was, the account
* setup can proceed. If Desktop doesn't yet have an account set up,
* it will keep the channel open and let the user connect to or
* create an account.
*
* | encrypt credentials
* |<------------- upload credentials
* retrieve credentials <-----------|
* verify HMAC |
* decrypt credentials |
* delete session ----------------->|
* start syncing |
*
*
* Create a client object like so:
*
* let client = new JPAKEClient(controller);
*
* The 'controller' object must implement the following methods:
*
* displayPIN(pin) -- Called when a PIN has been generated and is ready to
* be displayed to the user. Only called on the client where the pairing
* was initiated with 'receiveNoPIN()'.
*
* onPairingStart() -- Called when the pairing has started and messages are
* being sent back and forth over the channel. Only called on the client
* where the pairing was initiated with 'receiveNoPIN()'.
*
* onPaired() -- Called when the device pairing has been established and
* we're ready to send the credentials over. To do that, the controller
* must call 'sendAndComplete()' while the channel is active.
*
* onComplete(data) -- Called after transfer has been completed. On
* the sending side this is called with no parameter and as soon as the
* data has been uploaded. This does not mean the receiving side has
* actually retrieved them yet.
*
* onAbort(error) -- Called whenever an error is encountered. All errors lead
* to an abort and the process has to be started again on both sides.
*
* To start the data transfer on the receiving side, call
*
* client.receiveNoPIN();
*
* This will allocate a new channel on the server, generate a PIN, have it
* displayed and then do the transfer once the protocol has been completed
* with the sending side.
*
* To initiate the transfer from the sending side, call
*
* client.pairWithPIN(pin, true);
*
* Once the pairing has been established, the controller's 'onPaired()' method
* will be called. To then transmit the data, call
*
* client.sendAndComplete(data);
*
* To abort the process, call
*
* client.abort();
*
* Note that after completion or abort, the 'client' instance may not be reused.
* You will have to create a new one in case you'd like to restart the process.
*/
this.JPAKEClient = function JPAKEClient(controller) {
this.controller = controller;
this._log = Log.repository.getLogger("Sync.JPAKEClient");
this._log.level = Log.Level[Svc.Prefs.get(
"log.logger.service.jpakeclient", "Debug")];
this._serverURL = Svc.Prefs.get("jpake.serverURL");
this._pollInterval = Svc.Prefs.get("jpake.pollInterval");
this._maxTries = Svc.Prefs.get("jpake.maxTries");
if (this._serverURL.slice(-1) != "/") {
this._serverURL += "/";
}
this._jpake = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
.createInstance(Ci.nsISyncJPAKE);
this._setClientID();
}
JPAKEClient.prototype = {
_chain: Async.chain,
/*
* Public API
*/
/**
* Initiate pairing and receive data without providing a PIN. The PIN will
* be generated and passed on to the controller to be displayed to the user.
*
* This is typically called on mobile devices where typing is tedious.
*/
receiveNoPIN: function receiveNoPIN() {
this._my_signerid = JPAKE_SIGNERID_RECEIVER;
this._their_signerid = JPAKE_SIGNERID_SENDER;
this._secret = this._createSecret();
// Allow a large number of tries first while we wait for the PIN
// to be entered on the other device.
this._maxTries = Svc.Prefs.get("jpake.firstMsgMaxTries");
this._chain(this._getChannel,
this._computeStepOne,
this._putStep,
this._getStep,
function(callback) {
// We fetched the first response from the other client.
// Notify controller of the pairing starting.
Utils.nextTick(this.controller.onPairingStart,
this.controller);
// Now we can switch back to the smaller timeout.
this._maxTries = Svc.Prefs.get("jpake.maxTries");
callback();
},
this._computeStepTwo,
this._putStep,
this._getStep,
this._computeFinal,
this._computeKeyVerification,
this._putStep,
function(callback) {
// Allow longer time-out for the last message.
this._maxTries = Svc.Prefs.get("jpake.lastMsgMaxTries");
callback();
},
this._getStep,
this._decryptData,
this._complete)();
},
/**
* Initiate pairing based on the PIN entered by the user.
*
* This is typically called on desktop devices where typing is easier than
* on mobile.
*
* @param pin
* 12 character string (in human-friendly base32) containing the PIN
* entered by the user.
* @param expectDelay
* Flag that indicates that a significant delay between the pairing
* and the sending should be expected. v2 and earlier of the protocol
* did not allow for this and the pairing to a v2 or earlier client
* will be aborted if this flag is 'true'.
*/
pairWithPIN: function pairWithPIN(pin, expectDelay) {
this._my_signerid = JPAKE_SIGNERID_SENDER;
this._their_signerid = JPAKE_SIGNERID_RECEIVER;
this._channel = pin.slice(JPAKE_LENGTH_SECRET);
this._channelURL = this._serverURL + this._channel;
this._secret = pin.slice(0, JPAKE_LENGTH_SECRET);
this._chain(this._computeStepOne,
this._getStep,
function(callback) {
// Ensure that the other client can deal with a delay for
// the last message if that's requested by the caller.
if (!expectDelay) {
return callback();
}
if (!this._incoming.version || this._incoming.version < 3) {
return this.abort(JPAKE_ERROR_DELAYUNSUPPORTED);
}
return callback();
},
this._putStep,
this._computeStepTwo,
this._getStep,
this._putStep,
this._computeFinal,
this._getStep,
this._verifyPairing)();
},
/**
* Send data after a successful pairing.
*
* @param obj
* Object containing the data to send. It will be serialized as JSON.
*/
sendAndComplete: function sendAndComplete(obj) {
if (!this._paired || this._finished) {
this._log.error("Can't send data, no active pairing!");
throw "No active pairing!";
}
this._data = JSON.stringify(obj);
this._chain(this._encryptData,
this._putStep,
this._complete)();
},
/**
* Abort the current pairing. The channel on the server will be deleted
* if the abort wasn't due to a network or server error. The controller's
* 'onAbort()' method is notified in all cases.
*
* @param error [optional]
* Error constant indicating the reason for the abort. Defaults to
* user abort.
*/
abort: function abort(error) {
this._log.debug("Aborting...");
this._finished = true;
let self = this;
// Default to "user aborted".
if (!error) {
error = JPAKE_ERROR_USERABORT;
}
if (error == JPAKE_ERROR_CHANNEL ||
error == JPAKE_ERROR_NETWORK ||
error == JPAKE_ERROR_NODATA) {
Utils.nextTick(function() { this.controller.onAbort(error); }, this);
} else {
this._reportFailure(error, function() { self.controller.onAbort(error); });
}
},
/*
* Utilities
*/
_setClientID: function _setClientID() {
let rng = Cc["@mozilla.org/security/random-generator;1"]
.createInstance(Ci.nsIRandomGenerator);
let bytes = rng.generateRandomBytes(JPAKE_LENGTH_CLIENTID / 2);
this._clientID = bytes.map(byte => ("0" + byte.toString(16)).slice(-2)).join("");
},
_createSecret: function _createSecret() {
// 0-9a-z without 1,l,o,0
const key = "23456789abcdefghijkmnpqrstuvwxyz";
let rng = Cc["@mozilla.org/security/random-generator;1"]
.createInstance(Ci.nsIRandomGenerator);
let bytes = rng.generateRandomBytes(JPAKE_LENGTH_SECRET);
return bytes.map(byte => key[Math.floor(byte * key.length / 256)]).join("");
},
_newRequest: function _newRequest(uri) {
let request = new RESTRequest(uri);
request.setHeader("X-KeyExchange-Id", this._clientID);
request.timeout = REQUEST_TIMEOUT;
return request;
},
/*
* Steps of J-PAKE procedure
*/
_getChannel: function _getChannel(callback) {
this._log.trace("Requesting channel.");
let request = this._newRequest(this._serverURL + "new_channel");
request.get(Utils.bind2(this, function handleChannel(error) {
if (this._finished) {
return;
}
if (error) {
this._log.error("Error acquiring channel ID. " + error);
this.abort(JPAKE_ERROR_CHANNEL);
return;
}
if (request.response.status != 200) {
this._log.error("Error acquiring channel ID. Server responded with HTTP "
+ request.response.status);
this.abort(JPAKE_ERROR_CHANNEL);
return;
}
try {
this._channel = JSON.parse(request.response.body);
} catch (ex) {
this._log.error("Server responded with invalid JSON.");
this.abort(JPAKE_ERROR_CHANNEL);
return;
}
this._log.debug("Using channel " + this._channel);
this._channelURL = this._serverURL + this._channel;
// Don't block on UI code.
let pin = this._secret + this._channel;
Utils.nextTick(function() { this.controller.displayPIN(pin); }, this);
callback();
}));
},
// Generic handler for uploading data.
_putStep: function _putStep(callback) {
this._log.trace("Uploading message " + this._outgoing.type);
let request = this._newRequest(this._channelURL);
if (this._their_etag) {
request.setHeader("If-Match", this._their_etag);
} else {
request.setHeader("If-None-Match", "*");
}
request.put(this._outgoing, Utils.bind2(this, function(error) {
if (this._finished) {
return;
}
if (error) {
this._log.error("Error uploading data. " + error);
this.abort(JPAKE_ERROR_NETWORK);
return;
}
if (request.response.status != 200) {
this._log.error("Could not upload data. Server responded with HTTP "
+ request.response.status);
this.abort(JPAKE_ERROR_SERVER);
return;
}
// There's no point in returning early here since the next step will
// always be a GET so let's pause for twice the poll interval.
this._my_etag = request.response.headers["etag"];
Utils.namedTimer(function() { callback(); }, this._pollInterval * 2,
this, "_pollTimer");
}));
},
// Generic handler for polling for and retrieving data.
_pollTries: 0,
_getStep: function _getStep(callback) {
this._log.trace("Retrieving next message.");
let request = this._newRequest(this._channelURL);
if (this._my_etag) {
request.setHeader("If-None-Match", this._my_etag);
}
request.get(Utils.bind2(this, function(error) {
if (this._finished) {
return;
}
if (error) {
this._log.error("Error fetching data. " + error);
this.abort(JPAKE_ERROR_NETWORK);
return;
}
if (request.response.status == 304) {
this._log.trace("Channel hasn't been updated yet. Will try again later.");
if (this._pollTries >= this._maxTries) {
this._log.error("Tried for " + this._pollTries + " times, aborting.");
this.abort(JPAKE_ERROR_TIMEOUT);
return;
}
this._pollTries += 1;
Utils.namedTimer(function() { this._getStep(callback); },
this._pollInterval, this, "_pollTimer");
return;
}
this._pollTries = 0;
if (request.response.status == 404) {
this._log.error("No data found in the channel.");
this.abort(JPAKE_ERROR_NODATA);
return;
}
if (request.response.status != 200) {
this._log.error("Could not retrieve data. Server responded with HTTP "
+ request.response.status);
this.abort(JPAKE_ERROR_SERVER);
return;
}
this._their_etag = request.response.headers["etag"];
if (!this._their_etag) {
this._log.error("Server did not supply ETag for message: "
+ request.response.body);
this.abort(JPAKE_ERROR_SERVER);
return;
}
try {
this._incoming = JSON.parse(request.response.body);
} catch (ex) {
this._log.error("Server responded with invalid JSON.");
this.abort(JPAKE_ERROR_INVALID);
return;
}
this._log.trace("Fetched message " + this._incoming.type);
callback();
}));
},
_reportFailure: function _reportFailure(reason, callback) {
this._log.debug("Reporting failure to server.");
let request = this._newRequest(this._serverURL + "report");
request.setHeader("X-KeyExchange-Cid", this._channel);
request.setHeader("X-KeyExchange-Log", reason);
request.post("", Utils.bind2(this, function(error) {
if (error) {
this._log.warn("Report failed: " + error);
} else if (request.response.status != 200) {
this._log.warn("Report failed. Server responded with HTTP "
+ request.response.status);
}
// Do not block on errors, we're done or aborted by now anyway.
callback();
}));
},
_computeStepOne: function _computeStepOne(callback) {
this._log.trace("Computing round 1.");
let gx1 = {};
let gv1 = {};
let r1 = {};
let gx2 = {};
let gv2 = {};
let r2 = {};
try {
this._jpake.round1(this._my_signerid, gx1, gv1, r1, gx2, gv2, r2);
} catch (ex) {
this._log.error("JPAKE round 1 threw: " + ex);
this.abort(JPAKE_ERROR_INTERNAL);
return;
}
let one = {gx1: gx1.value,
gx2: gx2.value,
zkp_x1: {gr: gv1.value, b: r1.value, id: this._my_signerid},
zkp_x2: {gr: gv2.value, b: r2.value, id: this._my_signerid}};
this._outgoing = {type: this._my_signerid + "1",
version: KEYEXCHANGE_VERSION,
payload: one};
this._log.trace("Generated message " + this._outgoing.type);
callback();
},
_computeStepTwo: function _computeStepTwo(callback) {
this._log.trace("Computing round 2.");
if (this._incoming.type != this._their_signerid + "1") {
this._log.error("Invalid round 1 message: "
+ JSON.stringify(this._incoming));
this.abort(JPAKE_ERROR_WRONGMESSAGE);
return;
}
let step1 = this._incoming.payload;
if (!step1 || !step1.zkp_x1 || step1.zkp_x1.id != this._their_signerid
|| !step1.zkp_x2 || step1.zkp_x2.id != this._their_signerid) {
this._log.error("Invalid round 1 payload: " + JSON.stringify(step1));
this.abort(JPAKE_ERROR_WRONGMESSAGE);
return;
}
let A = {};
let gvA = {};
let rA = {};
try {
this._jpake.round2(this._their_signerid, this._secret,
step1.gx1, step1.zkp_x1.gr, step1.zkp_x1.b,
step1.gx2, step1.zkp_x2.gr, step1.zkp_x2.b,
A, gvA, rA);
} catch (ex) {
this._log.error("JPAKE round 2 threw: " + ex);
this.abort(JPAKE_ERROR_INTERNAL);
return;
}
let two = {A: A.value,
zkp_A: {gr: gvA.value, b: rA.value, id: this._my_signerid}};
this._outgoing = {type: this._my_signerid + "2",
version: KEYEXCHANGE_VERSION,
payload: two};
this._log.trace("Generated message " + this._outgoing.type);
callback();
},
_computeFinal: function _computeFinal(callback) {
if (this._incoming.type != this._their_signerid + "2") {
this._log.error("Invalid round 2 message: "
+ JSON.stringify(this._incoming));
this.abort(JPAKE_ERROR_WRONGMESSAGE);
return;
}
let step2 = this._incoming.payload;
if (!step2 || !step2.zkp_A || step2.zkp_A.id != this._their_signerid) {
this._log.error("Invalid round 2 payload: " + JSON.stringify(step1));
this.abort(JPAKE_ERROR_WRONGMESSAGE);
return;
}
let aes256Key = {};
let hmac256Key = {};
try {
this._jpake.final(step2.A, step2.zkp_A.gr, step2.zkp_A.b, HMAC_INPUT,
aes256Key, hmac256Key);
} catch (ex) {
this._log.error("JPAKE final round threw: " + ex);
this.abort(JPAKE_ERROR_INTERNAL);
return;
}
this._crypto_key = aes256Key.value;
let hmac_key = Utils.makeHMACKey(Utils.safeAtoB(hmac256Key.value));
this._hmac_hasher = Utils.makeHMACHasher(Ci.nsICryptoHMAC.SHA256, hmac_key);
callback();
},
_computeKeyVerification: function _computeKeyVerification(callback) {
this._log.trace("Encrypting key verification value.");
let iv, ciphertext;
try {
iv = Svc.Crypto.generateRandomIV();
ciphertext = Svc.Crypto.encrypt(JPAKE_VERIFY_VALUE,
this._crypto_key, iv);
} catch (ex) {
this._log.error("Failed to encrypt key verification value.");
this.abort(JPAKE_ERROR_INTERNAL);
return;
}
this._outgoing = {type: this._my_signerid + "3",
version: KEYEXCHANGE_VERSION,
payload: {ciphertext, IV: iv}};
this._log.trace("Generated message " + this._outgoing.type);
callback();
},
_verifyPairing: function _verifyPairing(callback) {
this._log.trace("Verifying their key.");
if (this._incoming.type != this._their_signerid + "3") {
this._log.error("Invalid round 3 data: " +
JSON.stringify(this._incoming));
this.abort(JPAKE_ERROR_WRONGMESSAGE);
return;
}
let step3 = this._incoming.payload;
let ciphertext;
try {
ciphertext = Svc.Crypto.encrypt(JPAKE_VERIFY_VALUE,
this._crypto_key, step3.IV);
if (ciphertext != step3.ciphertext) {
throw "Key mismatch!";
}
} catch (ex) {
this._log.error("Keys don't match!");
this.abort(JPAKE_ERROR_KEYMISMATCH);
return;
}
this._log.debug("Verified pairing!");
this._paired = true;
Utils.nextTick(function() { this.controller.onPaired(); }, this);
callback();
},
_encryptData: function _encryptData(callback) {
this._log.trace("Encrypting data.");
let iv, ciphertext, hmac;
try {
iv = Svc.Crypto.generateRandomIV();
ciphertext = Svc.Crypto.encrypt(this._data, this._crypto_key, iv);
hmac = Utils.bytesAsHex(Utils.digestUTF8(ciphertext, this._hmac_hasher));
} catch (ex) {
this._log.error("Failed to encrypt data.");
this.abort(JPAKE_ERROR_INTERNAL);
return;
}
this._outgoing = {type: this._my_signerid + "3",
version: KEYEXCHANGE_VERSION,
payload: {ciphertext, IV: iv, hmac}};
this._log.trace("Generated message " + this._outgoing.type);
callback();
},
_decryptData: function _decryptData(callback) {
this._log.trace("Verifying their key.");
if (this._incoming.type != this._their_signerid + "3") {
this._log.error("Invalid round 3 data: "
+ JSON.stringify(this._incoming));
this.abort(JPAKE_ERROR_WRONGMESSAGE);
return;
}
let step3 = this._incoming.payload;
try {
let hmac = Utils.bytesAsHex(
Utils.digestUTF8(step3.ciphertext, this._hmac_hasher));
if (hmac != step3.hmac) {
throw "HMAC validation failed!";
}
} catch (ex) {
this._log.error("HMAC validation failed.");
this.abort(JPAKE_ERROR_KEYMISMATCH);
return;
}
this._log.trace("Decrypting data.");
let cleartext;
try {
cleartext = Svc.Crypto.decrypt(step3.ciphertext, this._crypto_key,
step3.IV);
} catch (ex) {
this._log.error("Failed to decrypt data.");
this.abort(JPAKE_ERROR_INTERNAL);
return;
}
try {
this._newData = JSON.parse(cleartext);
} catch (ex) {
this._log.error("Invalid data data: " + JSON.stringify(cleartext));
this.abort(JPAKE_ERROR_INVALID);
return;
}
this._log.trace("Decrypted data.");
callback();
},
_complete: function _complete() {
this._log.debug("Exchange completed.");
this._finished = true;
Utils.nextTick(function() { this.controller.onComplete(this._newData); },
this);
}
};
/**
* Send credentials over an active J-PAKE channel.
*
* This object is designed to take over as the JPAKEClient controller,
* presumably replacing one that is UI-based which would either cause
* DOM objects to leak or the JPAKEClient to be GC'ed when the DOM
* context disappears. This object stays alive for the duration of the
* transfer by being strong-ref'ed as an nsIObserver.
*
* Credentials are sent after the first sync has been completed
* (successfully or not.)
*
* Usage:
*
* jpakeclient.controller = new SendCredentialsController(jpakeclient,
* service);
*
*/
this.SendCredentialsController =
function SendCredentialsController(jpakeclient, service) {
this._log = Log.repository.getLogger("Sync.SendCredentialsController");
this._log.level = Log.Level[Svc.Prefs.get("log.logger.service.main")];
this._log.trace("Loading.");
this.jpakeclient = jpakeclient;
this.service = service;
// Register ourselves as observers the first Sync finishing (either
// successfully or unsuccessfully, we don't care) or for removing
// this device's sync configuration, in case that happens while we
// haven't finished the first sync yet.
Services.obs.addObserver(this, "weave:service:sync:finish", false);
Services.obs.addObserver(this, "weave:service:sync:error", false);
Services.obs.addObserver(this, "weave:service:start-over", false);
}
SendCredentialsController.prototype = {
unload: function unload() {
this._log.trace("Unloading.");
try {
Services.obs.removeObserver(this, "weave:service:sync:finish");
Services.obs.removeObserver(this, "weave:service:sync:error");
Services.obs.removeObserver(this, "weave:service:start-over");
} catch (ex) {
// Ignore.
}
},
observe: function observe(subject, topic, data) {
switch (topic) {
case "weave:service:sync:finish":
case "weave:service:sync:error":
Utils.nextTick(this.sendCredentials, this);
break;
case "weave:service:start-over":
// This will call onAbort which will call unload().
this.jpakeclient.abort();
break;
}
},
sendCredentials: function sendCredentials() {
this._log.trace("Sending credentials.");
let credentials = {account: this.service.identity.account,
password: this.service.identity.basicPassword,
synckey: this.service.identity.syncKey,
serverURL: this.service.serverURL};
this.jpakeclient.sendAndComplete(credentials);
},
// JPAKEClient controller API
onComplete: function onComplete() {
this._log.debug("Exchange was completed successfully!");
this.unload();
// Schedule a Sync for soonish to fetch the data uploaded by the
// device with which we just paired.
this.service.scheduler.scheduleNextSync(this.service.scheduler.activeInterval);
},
onAbort: function onAbort(error) {
// It doesn't really matter why we aborted, but the channel is closed
// for sure, so we won't be able to do anything with it.
this._log.debug("Exchange was aborted with error: " + error);
this.unload();
},
// Irrelevant methods for this controller:
displayPIN: function displayPIN() {},
onPairingStart: function onPairingStart() {},
onPaired: function onPaired() {},
};

View File

@ -7,6 +7,7 @@ this.EXPORTED_SYMBOLS = ["Weave"];
this.Weave = {};
Components.utils.import("resource://services-sync/constants.js", Weave);
var lazies = {
"jpakeclient.js": ["JPAKEClient", "SendCredentialsController"],
"service.js": ["Service"],
"status.js": ["Status"],
"util.js": ["Utils", "Svc"]

View File

@ -35,7 +35,9 @@ this.SyncScheduler = function SyncScheduler(service) {
SyncScheduler.prototype = {
_log: Log.repository.getLogger("Sync.SyncScheduler"),
_fatalLoginStatus: [LOGIN_FAILED_NO_PASSPHRASE,
_fatalLoginStatus: [LOGIN_FAILED_NO_USERNAME,
LOGIN_FAILED_NO_PASSWORD,
LOGIN_FAILED_NO_PASSPHRASE,
LOGIN_FAILED_INVALID_PASSPHRASE,
LOGIN_FAILED_LOGIN_REJECTED],
@ -47,7 +49,14 @@ SyncScheduler.prototype = {
setDefaults: function setDefaults() {
this._log.trace("Setting SyncScheduler policy values to defaults.");
this.singleDeviceInterval = getThrottledIntervalPreference("scheduler.fxa.singleDeviceInterval");
let service = Cc["@mozilla.org/weave/service;1"]
.getService(Ci.nsISupports)
.wrappedJSObject;
let part = service.fxAccountsEnabled ? "fxa" : "sync11";
let prefSDInterval = "scheduler." + part + ".singleDeviceInterval";
this.singleDeviceInterval = getThrottledIntervalPreference(prefSDInterval);
this.idleInterval = getThrottledIntervalPreference("scheduler.idleInterval");
this.activeInterval = getThrottledIntervalPreference("scheduler.activeInterval");
this.immediateInterval = getThrottledIntervalPreference("scheduler.immediateInterval");

View File

@ -39,12 +39,7 @@ SyncStorageRequest.prototype = {
}
if (this.authenticator) {
let result = this.authenticator(this, method);
if (result && result.headers) {
for (let [k, v] of Object.entries(result.headers)) {
setHeader(k, v);
}
}
this.authenticator(this);
} else {
this._log.debug("No authenticator found.");
}

View File

@ -21,10 +21,10 @@ const KEYS_WBO = "keys";
Cu.import("resource://gre/modules/Preferences.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://services-common/async.js");
Cu.import("resource://services-sync/constants.js");
Cu.import("resource://services-sync/engines.js");
Cu.import("resource://services-sync/engines/clients.js");
Cu.import("resource://services-sync/identity.js");
Cu.import("resource://services-sync/policies.js");
Cu.import("resource://services-sync/record.js");
Cu.import("resource://services-sync/resource.js");
@ -33,6 +33,7 @@ Cu.import("resource://services-sync/stages/enginesync.js");
Cu.import("resource://services-sync/stages/declined.js");
Cu.import("resource://services-sync/status.js");
Cu.import("resource://services-sync/telemetry.js");
Cu.import("resource://services-sync/userapi.js");
Cu.import("resource://services-sync/util.js");
const ENGINE_MODULES = {
@ -68,6 +69,24 @@ Sync11Service.prototype = {
// world is ebbedded in the token returned from the token server.
_clusterURL: null,
get serverURL() {
return Svc.Prefs.get("serverURL");
},
set serverURL(value) {
if (!value.endsWith("/")) {
value += "/";
}
// Only do work if it's actually changing
if (value == this.serverURL)
return;
Svc.Prefs.set("serverURL", value);
// A new server most likely uses a different cluster, so clear that.
this._clusterURL = null;
},
get clusterURL() {
return this._clusterURL || "";
},
@ -79,6 +98,35 @@ Sync11Service.prototype = {
this._updateCachedURLs();
},
get miscAPI() {
// Append to the serverURL if it's a relative fragment
let misc = Svc.Prefs.get("miscURL");
if (misc.indexOf(":") == -1)
misc = this.serverURL + misc;
return misc + MISC_API_VERSION + "/";
},
/**
* The URI of the User API service.
*
* This is the base URI of the service as applicable to all users up to
* and including the server version path component, complete with trailing
* forward slash.
*/
get userAPIURI() {
// Append to the serverURL if it's a relative fragment.
let url = Svc.Prefs.get("userURL");
if (!url.includes(":")) {
url = this.serverURL + url;
}
return url + USER_API_VERSION + "/";
},
get pwResetURL() {
return this.serverURL + "weave-password-reset";
},
get syncID() {
// Generate a random syncID id we don't have one
let syncID = Svc.Prefs.get("client.syncID", "");
@ -124,7 +172,7 @@ Sync11Service.prototype = {
_updateCachedURLs: function _updateCachedURLs() {
// Nothing to cache yet if we don't have the building blocks
if (!this.clusterURL) {
if (!this.clusterURL || !this.identity.username) {
// Also reset all other URLs used by Sync to ensure we aren't accidentally
// using one cached earlier - if there's no cluster URL any cached ones
// are invalid.
@ -273,6 +321,14 @@ Sync11Service.prototype = {
onStartup: function onStartup() {
this._migratePrefs();
// Status is instantiated before us and is the first to grab an instance of
// the IdentityManager. We use that instance because IdentityManager really
// needs to be a singleton. Ideally, the longer-lived object would spawn
// this service instance.
if (!Status || !Status._authManager) {
throw new Error("Status or Status._authManager not initialized.");
}
this.status = Status;
this.identity = Status._authManager;
this.collectionKeys = new CollectionKeyManager();
@ -511,9 +567,21 @@ Sync11Service.prototype = {
this._log.debug("Fetching and verifying -- or generating -- symmetric keys.");
// Don't allow empty/missing passphrase.
// Furthermore, we assume that our sync key is already upgraded,
// and fail if that assumption is invalidated.
if (!this.identity.syncKey) {
this.status.login = LOGIN_FAILED_NO_PASSPHRASE;
this.status.sync = CREDENTIALS_CHANGED;
return false;
}
let syncKeyBundle = this.identity.syncKeyBundle;
if (!syncKeyBundle) {
this.status.login = LOGIN_FAILED_NO_PASSPHRASE;
this._log.error("Sync Key Bundle not set. Invalid Sync Key?");
this.status.login = LOGIN_FAILED_INVALID_PASSPHRASE;
this.status.sync = CREDENTIALS_CHANGED;
return false;
}
@ -649,7 +717,7 @@ Sync11Service.prototype = {
// We have no way of verifying the passphrase right now,
// so wait until remoteSetup to do so.
// Just make the most trivial checks.
if (!this.identity.syncKeyBundle) {
if (!this.identity.syncKey) {
this._log.warn("No passphrase in verifyLogin.");
this.status.login = LOGIN_FAILED_NO_PASSPHRASE;
return false;
@ -757,6 +825,49 @@ Sync11Service.prototype = {
}
},
changePassword: function changePassword(newPassword) {
let client = new UserAPI10Client(this.userAPIURI);
let cb = Async.makeSpinningCallback();
client.changePassword(this.identity.username,
this.identity.basicPassword, newPassword, cb);
try {
cb.wait();
} catch (ex) {
this._log.debug("Password change failed", ex);
return false;
}
// Save the new password for requests and login manager.
this.identity.basicPassword = newPassword;
this.persistLogin();
return true;
},
changePassphrase: function changePassphrase(newphrase) {
return this._catch(function doChangePasphrase() {
/* Wipe. */
this.wipeServer();
this.logout();
/* Set this so UI is updated on next run. */
this.identity.syncKey = newphrase;
this.persistLogin();
/* We need to re-encrypt everything, so reset. */
this.resetClient();
this.collectionKeys.clear();
/* Login and sync. This also generates new keys. */
this.sync();
Svc.Obs.notify("weave:service:change-passphrase", true);
return true;
})();
},
startOver: function startOver() {
this._log.trace("Invoking Service.startOver.");
Svc.Obs.notify("weave:engine:stop-tracking");
@ -781,7 +892,7 @@ Sync11Service.prototype = {
// possible, so let's fake for the CLIENT_NOT_CONFIGURED status for now
// by emptying the passphrase (we still need the password).
this._log.info("Service.startOver dropping sync key and logging out.");
this.identity.resetSyncKeyBundle();
this.identity.resetSyncKey();
this.status.login = LOGIN_FAILED_NO_PASSPHRASE;
this.logout();
Svc.Obs.notify("weave:service:start-over");
@ -801,8 +912,23 @@ Sync11Service.prototype = {
this.identity.deleteSyncCredentials();
// If necessary, reset the identity manager, then re-initialize it so the
// FxA manager is used. This is configurable via a pref - mainly for tests.
let keepIdentity = false;
try {
keepIdentity = Services.prefs.getBoolPref("services.sync-testing.startOverKeepIdentity");
} catch (_) { /* no such pref */ }
if (keepIdentity) {
Svc.Obs.notify("weave:service:start-over:finish");
return;
}
try {
this.identity.finalize();
// an observer so the FxA migration code can take some action before
// the new identity is created.
Svc.Obs.notify("weave:service:start-over:init-identity");
this.identity.username = "";
this.status.__authManager = null;
this.identity = Status._authManager;
this._clusterManager = this.identity.createClusterManager(this);
@ -815,7 +941,15 @@ Sync11Service.prototype = {
}
},
login: function login() {
persistLogin: function persistLogin() {
try {
this.identity.persistCredentials(true);
} catch (ex) {
this._log.info("Unable to persist credentials: " + ex);
}
},
login: function login(username, password, passphrase) {
function onNotify() {
this._loggedIn = false;
if (Services.io.offline) {
@ -823,6 +957,17 @@ Sync11Service.prototype = {
throw "Application is offline, login should not be called";
}
let initialStatus = this._checkSetup();
if (username) {
this.identity.username = username;
}
if (password) {
this.identity.basicPassword = password;
}
if (passphrase) {
this.identity.syncKey = passphrase;
}
if (this._checkSetup() == CLIENT_NOT_CONFIGURED) {
throw "Aborting login, client not configured.";
}
@ -838,6 +983,12 @@ Sync11Service.prototype = {
// Just let any errors bubble up - they've more context than we do!
cb.wait();
// Calling login() with parameters when the client was
// previously not configured means setup was completed.
if (initialStatus == CLIENT_NOT_CONFIGURED
&& (username || password || passphrase)) {
Svc.Obs.notify("weave:service:setup-complete");
}
this._updateCachedURLs();
this._log.info("User logged in successfully - verifying login.");
@ -866,6 +1017,45 @@ Sync11Service.prototype = {
Svc.Obs.notify("weave:service:logout:finish");
},
checkAccount: function checkAccount(account) {
let client = new UserAPI10Client(this.userAPIURI);
let cb = Async.makeSpinningCallback();
let username = this.identity.usernameFromAccount(account);
client.usernameExists(username, cb);
try {
let exists = cb.wait();
return exists ? "notAvailable" : "available";
} catch (ex) {
// TODO fix API convention.
return this.errorHandler.errorStr(ex);
}
},
createAccount: function createAccount(email, password,
captchaChallenge, captchaResponse) {
let client = new UserAPI10Client(this.userAPIURI);
// Hint to server to allow scripted user creation or otherwise
// ignore captcha.
if (Svc.Prefs.isSet("admin-secret")) {
client.adminSecret = Svc.Prefs.get("admin-secret", "");
}
let cb = Async.makeSpinningCallback();
client.createAccount(email, password, captchaChallenge, captchaResponse,
cb);
try {
cb.wait();
return null;
} catch (ex) {
return this.errorHandler.errorStr(ex.body);
}
},
// Note: returns false if we failed for a reason other than the server not yet
// supporting the api.
_fetchServerConfiguration() {
@ -1011,6 +1201,11 @@ Sync11Service.prototype = {
this.syncID = meta.payload.syncID;
this._log.debug("Clear cached values and take syncId: " + this.syncID);
if (!this.upgradeSyncKey(meta.payload.syncID)) {
this._log.warn("Failed to upgrade sync key. Failing remote setup.");
return false;
}
if (!this.verifyAndFetchSymmetricKeys(infoResponse)) {
this._log.warn("Failed to fetch symmetric keys. Failing remote setup.");
return false;
@ -1025,6 +1220,11 @@ Sync11Service.prototype = {
return true;
}
if (!this.upgradeSyncKey(meta.payload.syncID)) {
this._log.warn("Failed to upgrade sync key. Failing remote setup.");
return false;
}
if (!this.verifyAndFetchSymmetricKeys(infoResponse)) {
this._log.warn("Failed to fetch symmetric keys. Failing remote setup.");
return false;
@ -1163,10 +1363,139 @@ Sync11Service.prototype = {
this.recordManager.set(this.metaURL, meta);
},
/**
* Get a migration sentinel for the Firefox Accounts migration.
* Returns a JSON blob - it is up to callers of this to make sense of the
* data.
*
* Returns a promise that resolves with the sentinel, or null.
*/
getFxAMigrationSentinel() {
if (this._shouldLogin()) {
this._log.debug("In getFxAMigrationSentinel: should login.");
if (!this.login()) {
this._log.debug("Can't get migration sentinel: login returned false.");
return Promise.resolve(null);
}
}
if (!this.identity.syncKeyBundle) {
this._log.error("Can't get migration sentinel: no syncKeyBundle.");
return Promise.resolve(null);
}
try {
let collectionURL = this.storageURL + "meta/fxa_credentials";
let cryptoWrapper = this.recordManager.get(collectionURL);
if (!cryptoWrapper || !cryptoWrapper.payload) {
// nothing to decrypt - .decrypt is noisy in that case, so just bail
// now.
return Promise.resolve(null);
}
// If the payload has a sentinel it means we must have put back the
// decrypted version last time we were called.
if (cryptoWrapper.payload.sentinel) {
return Promise.resolve(cryptoWrapper.payload.sentinel);
}
// If decryption fails it almost certainly means the key is wrong - but
// it's not clear if we need to take special action for that case?
let payload = cryptoWrapper.decrypt(this.identity.syncKeyBundle);
// After decrypting the ciphertext is lost, so we just stash the
// decrypted payload back into the wrapper.
cryptoWrapper.payload = payload;
return Promise.resolve(payload.sentinel);
} catch (ex) {
this._log.error("Failed to fetch the migration sentinel: ${}", ex);
return Promise.resolve(null);
}
},
/**
* Set a migration sentinel for the Firefox Accounts migration.
* Accepts a JSON blob - it is up to callers of this to make sense of the
* data.
*
* Returns a promise that resolves with a boolean which indicates if the
* sentinel was successfully written.
*/
setFxAMigrationSentinel(sentinel) {
if (this._shouldLogin()) {
this._log.debug("In setFxAMigrationSentinel: should login.");
if (!this.login()) {
this._log.debug("Can't set migration sentinel: login returned false.");
return Promise.resolve(false);
}
}
if (!this.identity.syncKeyBundle) {
this._log.error("Can't set migration sentinel: no syncKeyBundle.");
return Promise.resolve(false);
}
try {
let collectionURL = this.storageURL + "meta/fxa_credentials";
let cryptoWrapper = new CryptoWrapper("meta", "fxa_credentials");
cryptoWrapper.cleartext.sentinel = sentinel;
cryptoWrapper.encrypt(this.identity.syncKeyBundle);
let res = this.resource(collectionURL);
let response = res.put(cryptoWrapper.toJSON());
if (!response.success) {
throw response;
}
this.recordManager.set(collectionURL, cryptoWrapper);
} catch (ex) {
this._log.error("Failed to set the migration sentinel: ${}", ex);
return Promise.resolve(false);
}
return Promise.resolve(true);
},
/**
* If we have a passphrase, rather than a 25-alphadigit sync key,
* use the provided sync ID to bootstrap it using PBKDF2.
*
* Store the new 'passphrase' back into the identity manager.
*
* We can check this as often as we want, because once it's done the
* check will no longer succeed. It only matters that it happens after
* we decide to bump the server storage version.
*/
upgradeSyncKey: function upgradeSyncKey(syncID) {
let p = this.identity.syncKey;
if (!p) {
return false;
}
// Check whether it's already a key that we generated.
if (Utils.isPassphrase(p)) {
this._log.info("Sync key is up-to-date: no need to upgrade.");
return true;
}
// Otherwise, let's upgrade it.
// N.B., we persist the sync key without testing it first...
let s = btoa(syncID); // It's what WeaveCrypto expects. *sigh*
let k = Utils.derivePresentableKeyFromPassphrase(p, s, PBKDF2_KEY_BYTES); // Base 32.
if (!k) {
this._log.error("No key resulted from derivePresentableKeyFromPassphrase. Failing upgrade.");
return false;
}
this._log.info("Upgrading sync key...");
this.identity.syncKey = k;
this._log.info("Saving upgraded sync key...");
this.persistLogin();
this._log.info("Done saving.");
return true;
},
_freshStart: function _freshStart() {
this._log.info("Fresh start. Resetting client.");
this._log.info("Fresh start. Resetting client and considering key upgrade.");
this.resetClient();
this.collectionKeys.clear();
this.upgradeSyncKey(this.syncID);
// Wipe the server.
this.wipeServer();
@ -1275,6 +1604,9 @@ Sync11Service.prototype = {
engine.wipeClient();
}
}
// Save the password/passphrase just in-case they aren't restored by sync
this.persistLogin();
},
/**

View File

@ -0,0 +1,113 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
this.EXPORTED_SYMBOLS = ["ClusterManager"];
var {utils: Cu} = Components;
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://services-sync/constants.js");
Cu.import("resource://services-sync/policies.js");
Cu.import("resource://services-sync/util.js");
/**
* Contains code for managing the Sync cluster we are in.
*/
this.ClusterManager = function ClusterManager(service) {
this._log = Log.repository.getLogger("Sync.Service");
this._log.level = Log.Level[Svc.Prefs.get("log.logger.service.main")];
this.service = service;
}
ClusterManager.prototype = {
get identity() {
return this.service.identity;
},
/**
* Obtain the cluster for the current user.
*
* Returns the string URL of the cluster or null on error.
*/
_findCluster: function _findCluster() {
this._log.debug("Finding cluster for user " + this.identity.username);
// This should ideally use UserAPI10Client but the legacy hackiness is
// strong with this code.
let fail;
let url = this.service.userAPIURI + this.identity.username + "/node/weave";
let res = this.service.resource(url);
try {
let node = res.get();
switch (node.status) {
case 400:
this.service.status.login = LOGIN_FAILED_LOGIN_REJECTED;
fail = "Find cluster denied: " + this.service.errorHandler.errorStr(node);
break;
case 404:
this._log.debug("Using serverURL as data cluster (multi-cluster support disabled)");
return this.service.serverURL;
case 0:
case 200:
if (node == "null") {
node = null;
}
this._log.trace("_findCluster successfully returning " + node);
return node;
default:
this.service.errorHandler.checkServerError(node);
fail = "Unexpected response code: " + node.status;
break;
}
} catch (e) {
this._log.debug("Network error on findCluster");
this.service.status.login = LOGIN_FAILED_NETWORK_ERROR;
this.service.errorHandler.checkServerError(e);
fail = e;
}
throw fail;
},
/**
* Determine the cluster for the current user and update state.
*/
setCluster: function setCluster() {
// Make sure we didn't get some unexpected response for the cluster.
let cluster = this._findCluster();
this._log.debug("Cluster value = " + cluster);
if (cluster == null) {
return false;
}
// Convert from the funky "String object with additional properties" that
// resource.js returns to a plain-old string.
cluster = cluster.toString();
// Don't update stuff if we already have the right cluster
if (cluster == this.service.clusterURL) {
return false;
}
this._log.debug("Setting cluster to " + cluster);
this.service.clusterURL = cluster;
return true;
},
getUserBaseURL: function getUserBaseURL() {
// Legacy Sync and FxA Sync construct the userBaseURL differently. Legacy
// Sync appends path components onto an empty path, and in FxA Sync, the
// token server constructs this for us in an opaque manner. Since the
// cluster manager already sets the clusterURL on Service and also has
// access to the current identity, we added this functionality here.
// If the clusterURL hasn't been set, the userBaseURL shouldn't be set
// either. Some tests expect "undefined" to be returned here.
if (!this.service.clusterURL) {
return undefined;
}
let storageAPI = this.service.clusterURL + SYNC_API_VERSION + "/";
return storageAPI + this.identity.username + "/";
}
};
Object.freeze(ClusterManager.prototype);

View File

@ -11,6 +11,7 @@ var Cu = Components.utils;
Cu.import("resource://services-sync/constants.js");
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://services-sync/identity.js");
Cu.import("resource://services-sync/browserid_identity.js");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://services-common/async.js");
@ -24,7 +25,11 @@ this.Status = {
if (this.__authManager) {
return this.__authManager;
}
this.__authManager = new BrowserIDManager();
let service = Components.classes["@mozilla.org/weave/service;1"]
.getService(Components.interfaces.nsISupports)
.wrappedJSObject;
let idClass = service.fxAccountsEnabled ? BrowserIDManager : IdentityManager;
this.__authManager = new idClass();
this.__authManager.initialize();
return this.__authManager;
},
@ -47,6 +52,7 @@ this.Status = {
this._login = code;
if (code == LOGIN_FAILED_NO_USERNAME ||
code == LOGIN_FAILED_NO_PASSWORD ||
code == LOGIN_FAILED_NO_PASSPHRASE) {
this.service = CLIENT_NOT_CONFIGURED;
} else if (code != LOGIN_SUCCEEDED) {

View File

@ -0,0 +1,219 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
this.EXPORTED_SYMBOLS = [
"UserAPI10Client",
];
var {utils: Cu} = Components;
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://services-common/rest.js");
Cu.import("resource://services-common/utils.js");
Cu.import("resource://services-sync/identity.js");
Cu.import("resource://services-sync/util.js");
/**
* A generic client for the user API 1.0 service.
*
* http://docs.services.mozilla.com/reg/apis.html
*
* Instances are constructed with the base URI of the service.
*/
this.UserAPI10Client = function UserAPI10Client(baseURI) {
this._log = Log.repository.getLogger("Sync.UserAPI");
this._log.level = Log.Level[Svc.Prefs.get("log.logger.userapi")];
this.baseURI = baseURI;
}
UserAPI10Client.prototype = {
USER_CREATE_ERROR_CODES: {
2: "Incorrect or missing captcha.",
4: "User exists.",
6: "JSON parse failure.",
7: "Missing password field.",
9: "Requested password not strong enough.",
12: "No email address on file.",
},
/**
* Determine whether a specified username exists.
*
* Callback receives the following arguments:
*
* (Error) Describes error that occurred or null if request was
* successful.
* (boolean) True if user exists. False if not. null if there was an error.
*/
usernameExists: function usernameExists(username, cb) {
if (typeof(cb) != "function") {
throw new Error("cb must be a function.");
}
let url = this.baseURI + username;
let request = new RESTRequest(url);
request.get(this._onUsername.bind(this, cb, request));
},
/**
* Obtain the Weave (Sync) node for a specified user.
*
* The callback receives the following arguments:
*
* (Error) Describes error that occurred or null if request was successful.
* (string) Username request is for.
* (string) URL of user's node. If null and there is no error, no node could
* be assigned at the time of the request.
*/
getWeaveNode: function getWeaveNode(username, password, cb) {
if (typeof(cb) != "function") {
throw new Error("cb must be a function.");
}
let request = this._getRequest(username, "/node/weave", password);
request.get(this._onWeaveNode.bind(this, cb, request));
},
/**
* Change a password for the specified user.
*
* @param username
* (string) The username whose password to change.
* @param oldPassword
* (string) The old, current password.
* @param newPassword
* (string) The new password to switch to.
*/
changePassword: function changePassword(username, oldPassword, newPassword, cb) {
let request = this._getRequest(username, "/password", oldPassword);
request.onComplete = this._onChangePassword.bind(this, cb, request);
request.post(CommonUtils.encodeUTF8(newPassword));
},
createAccount: function createAccount(email, password, captchaChallenge,
captchaResponse, cb) {
let username = IdentityManager.prototype.usernameFromAccount(email);
let body = JSON.stringify({
"email": email,
"password": Utils.encodeUTF8(password),
"captcha-challenge": captchaChallenge,
"captcha-response": captchaResponse
});
let url = this.baseURI + username;
let request = new RESTRequest(url);
if (this.adminSecret) {
request.setHeader("X-Weave-Secret", this.adminSecret);
}
request.onComplete = this._onCreateAccount.bind(this, cb, request);
request.put(body);
},
_getRequest: function _getRequest(username, path, password = null) {
let url = this.baseURI + username + path;
let request = new RESTRequest(url);
if (password) {
let up = username + ":" + password;
request.setHeader("authorization", "Basic " + btoa(up));
}
return request;
},
_onUsername: function _onUsername(cb, request, error) {
if (error) {
cb(error, null);
return;
}
let body = request.response.body;
if (body == "0") {
cb(null, false);
} else if (body == "1") {
cb(null, true);
} else {
cb(new Error("Unknown response from server: " + body), null);
}
},
_onWeaveNode: function _onWeaveNode(cb, request, error) {
if (error) {
cb.network = true;
cb(error, null);
return;
}
let response = request.response;
if (response.status == 200) {
let body = response.body;
if (body == "null") {
cb(null, null);
return;
}
cb(null, body);
return;
}
error = new Error("Sync node retrieval failed.");
switch (response.status) {
case 400:
error.denied = true;
break;
case 404:
error.notFound = true;
break;
default:
error.message = "Unexpected response code: " + response.status;
}
cb(error, null);
},
_onChangePassword: function _onChangePassword(cb, request, error) {
this._log.info("Password change response received: " +
request.response.status);
if (error) {
cb(error);
return;
}
let response = request.response;
if (response.status != 200) {
cb(new Error("Password changed failed: " + response.body));
return;
}
cb(null);
},
_onCreateAccount: function _onCreateAccount(cb, request, error) {
let response = request.response;
this._log.info("Create account response: " + response.status + " " +
response.body);
if (error) {
cb(new Error("HTTP transport error."), null);
return;
}
if (response.status == 200) {
cb(null, response.body);
return;
}
error = new Error("Could not create user.");
error.body = response.body;
cb(error, null);
},
};
Object.freeze(UserAPI10Client.prototype);

View File

@ -493,6 +493,8 @@ this.Utils = {
* take a presentable passphrase and reduce it to a normalized
* representation for storage. normalizePassphrase can safely be called
* on normalized input.
* * normalizeAccount:
* take user input for account/username, cleaning up appropriately.
*/
isPassphrase(s) {
@ -562,6 +564,10 @@ this.Utils = {
return pp;
},
normalizeAccount: function normalizeAccount(acc) {
return acc.trim();
},
/**
* Create an array like the first but without elements of the second. Reuse
* arrays if possible.

View File

@ -23,6 +23,9 @@ EXTRA_JS_MODULES['services-sync'] += [
'modules/browserid_identity.js',
'modules/collection_validator.js',
'modules/engines.js',
'modules/FxaMigrator.jsm',
'modules/identity.js',
'modules/jpakeclient.js',
'modules/keys.js',
'modules/main.js',
'modules/policies.js',
@ -33,6 +36,7 @@ EXTRA_JS_MODULES['services-sync'] += [
'modules/status.js',
'modules/SyncedTabs.jsm',
'modules/telemetry.js',
'modules/userapi.js',
'modules/util.js',
]
@ -57,6 +61,7 @@ EXTRA_JS_MODULES['services-sync'].engines += [
]
EXTRA_JS_MODULES['services-sync'].stages += [
'modules/stages/cluster.js',
'modules/stages/declined.js',
'modules/stages/enginesync.js',
]

View File

@ -2,6 +2,14 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
pref("services.sync.serverURL", "https://auth.services.mozilla.com/");
pref("services.sync.userURL", "user/");
pref("services.sync.miscURL", "misc/");
pref("services.sync.termsURL", "https://services.mozilla.com/tos/");
pref("services.sync.privacyURL", "https://services.mozilla.com/privacy-policy/");
pref("services.sync.statusURL", "https://services.mozilla.com/status/");
pref("services.sync.syncKeyHelpURL", "https://services.mozilla.com/help/synckey");
pref("services.sync.lastversion", "firstrun");
pref("services.sync.sendVersionInfo", true);
@ -12,6 +20,7 @@ pref("services.sync.scheduler.immediateInterval", 90); // 1.5 minutes
pref("services.sync.scheduler.idleTime", 300); // 5 minutes
pref("services.sync.scheduler.fxa.singleDeviceInterval", 3600); // 1 hour
pref("services.sync.scheduler.sync11.singleDeviceInterval", 86400); // 1 day
pref("services.sync.errorhandler.networkFailureReportTimeout", 1209600); // 2 weeks
@ -23,6 +32,12 @@ pref("services.sync.engine.prefs", true);
pref("services.sync.engine.tabs", true);
pref("services.sync.engine.tabs.filteredUrls", "^(about:.*|resource:.*|chrome:.*|wyciwyg:.*|file:.*|blob:.*)$");
pref("services.sync.jpake.serverURL", "https://setup.services.mozilla.com/");
pref("services.sync.jpake.pollInterval", 1000);
pref("services.sync.jpake.firstMsgMaxTries", 300); // 5 minutes
pref("services.sync.jpake.lastMsgMaxTries", 300); // 5 minutes
pref("services.sync.jpake.maxTries", 10);
// If true, add-on sync ignores changes to the user-enabled flag. This
// allows people to have the same set of add-ons installed across all
// profiles while maintaining different enabled states.
@ -44,6 +59,7 @@ pref("services.sync.log.logger.service.main", "Debug");
pref("services.sync.log.logger.status", "Debug");
pref("services.sync.log.logger.authenticator", "Debug");
pref("services.sync.log.logger.network.resources", "Debug");
pref("services.sync.log.logger.service.jpakeclient", "Debug");
pref("services.sync.log.logger.engine.bookmarks", "Debug");
pref("services.sync.log.logger.engine.clients", "Debug");
pref("services.sync.log.logger.engine.forms", "Debug");
@ -55,6 +71,7 @@ pref("services.sync.log.logger.engine.addons", "Debug");
pref("services.sync.log.logger.engine.extension-storage", "Debug");
pref("services.sync.log.logger.engine.apps", "Debug");
pref("services.sync.log.logger.identity", "Debug");
pref("services.sync.log.logger.userapi", "Debug");
pref("services.sync.log.cryptoDebug", false);
pref("services.sync.fxa.termsURL", "https://accounts.firefox.com/legal/terms");

View File

@ -23,11 +23,6 @@ function return_timestamp(request, response, timestamp) {
return timestamp;
}
function has_hawk_header(req) {
return req.hasHeader("Authorization") &&
req.getHeader("Authorization").startsWith("Hawk");
}
function basic_auth_header(user, password) {
return "Basic " + btoa(user + ":" + Utils.encodeUTF8(password));
}

View File

@ -49,6 +49,7 @@ async function setup() {
async function cleanup(server) {
Svc.Obs.notify("weave:engine:stop-tracking");
Services.prefs.setBoolPref("services.sync-testing.startOverKeepIdentity", true);
let promiseStartOver = promiseOneObserver("weave:service:start-over:finish");
Service.startOver();
await promiseStartOver;

View File

@ -83,6 +83,7 @@ add_task(async function test_initialializeWithCurrentIdentity() {
await browseridManager.whenReadyToAuthenticate.promise;
do_check_true(!!browseridManager._token);
do_check_true(browseridManager.hasValidToken());
do_check_eq(browseridManager.account, identityConfig.fxaccount.user.email);
}
);
@ -130,8 +131,10 @@ add_task(async function test_initialializeWithAuthErrorAndDeletedAccount() {
do_check_true(signCertificateCalled);
do_check_true(accountStatusCalled);
do_check_false(browseridManager.account);
do_check_false(browseridManager._token);
do_check_false(browseridManager.hasValidToken());
do_check_false(browseridManager.account);
});
add_task(async function test_initialializeWithNoKeys() {
@ -493,8 +496,10 @@ add_task(async function test_refreshCertificateOn401() {
do_check_eq(getCertCount, 2);
do_check_true(didReturn401);
do_check_true(didReturn200);
do_check_true(browseridManager.account);
do_check_true(browseridManager._token);
do_check_true(browseridManager.hasValidToken());
do_check_true(browseridManager.account);
});

View File

@ -102,7 +102,7 @@ add_task(async function test_bad_hmac() {
try {
await configureIdentity({username: "foo"}, server);
Service.login();
Service.login("foo");
generateNewKeys(Service.collectionKeys);

View File

@ -6,7 +6,7 @@ Cu.import("resource://services-sync/service.js");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/utils.js");
add_task(async function test_missing_crypto_collection() {
add_identity_test(this, async function test_missing_crypto_collection() {
let johnHelper = track_collections_helper();
let johnU = johnHelper.with_updated_collection;
let johnColls = johnHelper.collections;

Some files were not shown because too many files have changed in this diff Show More