This repository has been archived by the owner on Jan 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 132
/
sync.js
348 lines (314 loc) · 10.3 KB
/
sync.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/* exported loadFromKinto */
/* exported saveToKinto */
/* exported BrowserStorageCredentials */
let syncDebounce = null;
const cryptographer = new Jose.WebCryptographer();
cryptographer.setKeyEncryptionAlgorithm('A256KW');
cryptographer.setContentEncryptionAlgorithm('A256GCM');
function shared_key(key) {
return crypto.subtle.importKey(
'jwk',
{ kty: key.kty, k: key.k.replace(/=/, '') },
'AES-KW',
true,
['wrapKey', 'unwrapKey']
);
}
function encrypt(key, content) {
const encrypter = new JoseJWE.Encrypter(cryptographer, shared_key(key));
return encrypter.encrypt(JSON.stringify(content));
}
function decrypt(key, encrypted) {
const decrypter = new JoseJWE.Decrypter(cryptographer, shared_key(key));
return decrypter.decrypt(encrypted).then(result => {
return JSON.parse(result);
});
}
// An "id schema" used to validate Kinto IDs and generate new ones.
const notesIdSchema = {
// FIXME: Maybe this should generate IDs?
generate() {
throw new Error('cannot generate IDs');
},
validate() {
// FIXME: verify that at least this matches Kinto server ID format
return true;
},
};
class ServerKeyNewerError extends Error {
constructor() {
super('key used to encrypt the record appears to be newer than our key');
}
}
class ServerKeyOlderError extends Error {
constructor() {
super('key used to encrypt the record appears to be older than our key');
}
}
class JWETransformer {
constructor(key) {
this.key = key;
}
async encode(record) {
// FIXME: should we try to obfuscate the record ID?
const ciphertext = await encrypt(this.key, record);
// Copy over the _status field, so that we handle concurrency
// headers (If-Match, If-None-Match) correctly.
// DON'T copy over "deleted" status, because then we'd leak
// plaintext deletes.
const status = record._status && (record._status === 'deleted' ? 'updated' : record._status);
const encryptedResult = {
content: ciphertext,
id: record.id,
_status: status,
kid: this.key.kid,
};
if (record.hasOwnProperty('last_modified')) {
encryptedResult.last_modified = record.last_modified;
}
return encryptedResult;
}
async decode(record) {
if (!record.content) {
// This can happen for tombstones if a record is deleted.
if (record.deleted) {
return record;
}
throw new Error('No ciphertext: nothing to decrypt?');
}
if (record.kid !== this.key.kid) {
if (this.key.kid < record.kid) {
throw new ServerKeyNewerError();
} else {
throw new ServerKeyOlderError();
}
}
let decoded = await decrypt(this.key, record.content);
if (!decoded.hasOwnProperty('id')) {
// Old-style encrypted notes aren't true Kinto records --
// they're just the content field.
decoded = {
content: decoded,
id: 'singleNote',
};
}
if (record.hasOwnProperty('last_modified')) {
decoded.last_modified = record.last_modified;
}
// _status: deleted records were deleted on a client, but
// uploaded as an encrypted blob so we don't leak deletions.
// If we get such a record, flag it as deleted.
if (decoded._status === 'deleted') {
decoded.deleted = true;
}
return decoded;
}
}
/**
* Interface describing a mechanism to fetch credentials.
*/
class Credentials {
async get() {
return Promise.reject('Implement me');
}
/**
* Call this if, for example, credentials were invalid.
*/
async clear() {
return Promise.reject('Implement me');
}
}
class BrowserStorageCredentials extends Credentials {
constructor(storage) {
super();
this.storage = storage;
}
async get() {
const data = await this.storage.get(['credentials']);
return data.credentials;
}
async set(credentials) {
return this.storage.set({credentials});
}
async clear() {
return this.storage.remove('credentials');
}
}
/**
* Try to sync our data against the Kinto server.
*
* Returns a promise. The promise can reject in case of sync failure
* or any other reason. This is so that programming errors can be
* caught more easily in testing. Since this application is
* offline-first, sync failure should not be a failure for callers.
*/
function syncKinto(client, credentials) {
// Get credentials and lastmodified
let collection, credential;
return credentials.get()
.then(received => {
credential = received;
if (!received) return;
return fxaRenewCredential(credential)
.then((renewedCred) => {
credential = renewedCred;
return credentials.set(renewedCred);
})
.then(() => {
// Query Kinto with the Bearer Token
collection = client
.collection('notes', {
idSchema: notesIdSchema,
remoteTransformers: [new JWETransformer(credential.key)],
});
return collection
.sync({
headers: {Authorization: `Bearer ${credential.access_token}`},
strategy: 'manual',
});
});
})
.then(syncResult => {
// FIXME: Do we need to do anything with errors, published,
// updated, etc.?
if (syncResult && syncResult.conflicts.length > 0) {
return Promise.all(syncResult.conflicts.map(conflict => {
let resolution;
if (conflict.remote === null) {
resolution = {
id: conflict.local.id,
content: conflict.local.content,
};
} else {
const mergeWarning = browser.i18n.getMessage('mergeWarning');
let totalOps = conflict.remote.content;
totalOps += `\n${mergeWarning}\n\n`;
totalOps += conflict.local.content;
client.conflict = true;
resolution = {
id: conflict.remote.id,
content: totalOps,
};
sendMetrics('handle-conflict'); // eslint-disable-line no-undef
}
return collection.resolve(conflict, resolution);
}))
.then(() => {
return syncKinto(client, credentials);
});
}
})
.catch(error => {
if (error.response && error.response.status === 401) {
// In case of 401 log the user out.
// FIXME: Fetch a new token and retry?
return reconnectSync(credentials);
} else if (error instanceof ServerKeyNewerError) {
// If the key date is greater than current one, log the user out.
console.error(error); // eslint-disable-line no-console
return reconnectSync(credentials);
} else if (error instanceof ServerKeyOlderError) {
// If the key date is older than the current one, we can't help
// because there is no way we get the previous key.
// Flush the server because whatever was there is wrong.
console.error(error); // eslint-disable-line no-console
const kintoHttp = client.api;
return kintoHttp.bucket('default').deleteCollection('notes', {
headers: { Authorization: `Bearer ${credential.access_token}` }
}).then(() => collection.resetSyncStatus())
.then(() => syncKinto(client, credentials));
} else if (error.message.includes('flushed')) {
return collection.resetSyncStatus()
.then(() => {
return syncKinto(client, credentials);
});
} else if (error.message.includes('syncResult is undefined')) {
return Promise.resolve(null);
} else if (error.message === 'Failed to renew token') {
// cannot refresh the access token, log the user out.
return reconnectSync(credentials);
} else {
console.error(error); // eslint-disable-line no-console
reconnectSync(credentials);
return Promise.reject(error);
}
});
}
function reconnectSync(credentials) {
credentials.clear();
browser.runtime.sendMessage('notes@mozilla.com', {
action: 'reconnect'
});
}
function retrieveNote(client) {
return client.collection('notes', {
idSchema: notesIdSchema,
}).getAny('singleNote');
}
/**
* Try to sync against the Kinto server, and retrieve the current note
* contents.
*
* On completion, a 'kinto-loaded' event will be fired with the
* following structure:
*
* {
* action: 'kinto-loaded',
* data: the "content" that was previously saved to Kinto, or null
* if nothing was previously saved to Kinto (for example, a new
* FxA account, or if syncing failed on a fresh profile)
* last_modified: the timestamp of the sync, or null
* }
*/
function loadFromKinto(client, credentials) {
return syncKinto(client, credentials)
// Ignore failure of syncKinto by retrieving note even when promise rejected
.then(() => retrieveNote(client), () => retrieveNote(client))
.then(result => {
browser.runtime.sendMessage({
action: 'kinto-loaded',
data: result && typeof result.data !== 'undefined' ? result.data.content : null,
last_modified: result && typeof result.data !== 'undefined' && typeof result.data.last_modified !== 'undefined' ? result.data.last_modified : null,
});
});
}
function saveToKinto(client, credentials, content) {
let resolve;
const promise = new Promise(thisResolve => {
resolve = thisResolve;
});
// XXX: Debounce the call and set the status to Editing
browser.runtime.sendMessage('notes@mozilla.com', {
action: 'text-editing'
});
const later = function() {
syncDebounce = null;
const notes = client.collection('notes', {
idSchema: notesIdSchema,
});
return notes.upsert({ id: 'singleNote', content })
.then(() => {
browser.runtime.sendMessage('notes@mozilla.com', {
action: 'text-saved'
});
client.conflict = false;
return syncKinto(client, credentials);
})
.then(() => retrieveNote(client), () => retrieveNote(client))
.then(result => {
// Set the status to synced
return browser.runtime.sendMessage('notes@mozilla.com', {
action: 'text-synced',
content: result.data.content,
last_modified: result.data.last_modified,
conflict: client.conflict
});
})
.then(() => {
resolve();
});
};
clearTimeout(syncDebounce);
syncDebounce = setTimeout(later, 1000);
return promise;
}