-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlocalFirebase.js
366 lines (311 loc) · 10.6 KB
/
localFirebase.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/*
* firebase-server 0.7.1
* License: MIT.
* Copyright (C) 2013, 2014, 2015, 2016, Uri Shaked.
*/
'use strict'
var _ = require('lodash')
var WebSocketServer = require('ws').Server
var Ruleset = require('targaryen/lib/ruleset')
var RuleDataSnapshot = require('targaryen/lib/rule-data-snapshot')
var firebaseHash = require('./lib/firebaseHash')
var TestableClock = require('./lib/testable-clock')
var TokenValidator = require('./lib/token-validator')
var Promise = require('any-promise')
var firebase = require('firebase')
var _log = require('debug')('firebase-server')
// In order to produce new Firebase clients that do not conflict with existing
// instances of the Firebase client, each one must have a unique name.
// We use this incrementing number to ensure that each Firebase App name we
// create is unique.
var serverID = 0
function getSnap (ref) {
return new Promise(function (resolve) {
ref.once('value', function (snap) {
resolve(snap)
})
})
}
function exportData (ref) {
return getSnap(ref).then(function (snap) {
return snap.exportVal()
})
}
function normalizePath (fullPath) {
var path = fullPath
var isPriorityPath = /\/?\.priority$/.test(path)
if (isPriorityPath) {
path = path.replace(/\/?\.priority$/, '')
}
return {
isPriorityPath: isPriorityPath,
path: path,
fullPath: fullPath
}
}
function FirebaseServer (port, name, data) {
this.name = name || 'mock.firebase.server'
// Firebase is more than just a "database" now; the "realtime database" is
// just one of many services provided by a Firebase "App" container.
// The Firebase library must be initialized with an App, and that app
// must have a name - either a name you choose, or '[DEFAULT]' which
// the library will substitute for you if you do not provide one.
// An important aspect of App names is that multiple instances of the
// Firebase client with the same name will share a local cache instead of
// talking "through" our server. So to prevent that from happening, we are
// choosing a probably-unique name that a developer would not choose for
// their "real" Firebase client instances.
var appName = 'firebase-server-internal-' + this.name + '-' + serverID++
// We must pass a "valid looking" configuration to initializeApp for its
// internal checks to pass.
var config = {
databaseURL: 'ws://fakeserver.firebaseio.test'
}
this.app = firebase.initializeApp(config, appName)
this.app.database().goOffline()
this.baseRef = this.app.database().ref()
this.baseRef.set(data || null)
this._wss = new WebSocketServer({
port: port
})
this._clock = new TestableClock()
this._tokenValidator = new TokenValidator(null, this._clock)
this._wss.on('connection', this.handleConnection.bind(this))
_log('Listening for connections on port ' + port)
}
FirebaseServer.prototype = {
handleConnection: function (ws) {
_log('New connection from ' + ws._socket.remoteAddress + ':' + ws._socket.remotePort)
var server = this
var authToken = null
function send (message) {
var payload = JSON.stringify(message)
_log('Sending message: ' + payload)
try {
ws.send(payload)
} catch (e) {
_log('Send failed: ' + e)
}
}
function authData () {
var data
if (authToken) {
try {
data = server._tokenValidator.decode(authToken).d
} catch (e) {
authToken = null
}
}
return data
}
function pushData (path, data) {
send({d: {a: 'd', b: {p: path, d: data}}, t: 'd'})
}
function permissionDenied (requestId) {
send({d: {r: requestId, b: {s: 'permission_denied', d: 'Permission denied'}}, t: 'd'})
}
function replaceServerTimestamp (data) {
if (_.isEqual(data, firebase.database.ServerValue.TIMESTAMP)) {
return server._clock()
} else if (_.isObject(data)) {
return _.mapValues(data, replaceServerTimestamp)
} else {
return data
}
}
function ruleSnapshot (fbRef) {
return exportData(fbRef.root).then(function (exportVal) {
return new RuleDataSnapshot(RuleDataSnapshot.convert(exportVal))
})
}
function tryRead (requestId, path, fbRef) {
if (server._ruleset) {
return ruleSnapshot(fbRef).then(function (dataSnap) {
var result = server._ruleset.tryRead(path, dataSnap, authData())
if (!result.allowed) {
permissionDenied(requestId)
throw new Error('Permission denied for client to read from ' + path + ': ' + result.info)
}
return true
})
}
return Promise.resolve(true)
}
function tryWrite (requestId, path, fbRef, newData) {
if (server._ruleset) {
return ruleSnapshot(fbRef).then(function (dataSnap) {
var result = server._ruleset.tryWrite(path, dataSnap, newData, authData())
if (!result.allowed) {
permissionDenied(requestId)
throw new Error('Permission denied for client to write to ' + path + ': ' + result.info)
}
return true
})
}
return Promise.resolve(true)
}
function handleListen (requestId, normalizedPath, fbRef) {
var path = normalizedPath.path
_log('Client listen ' + path)
tryRead(requestId, path, fbRef)
.then(function () {
var sendOk = true
fbRef.on('value', function (snap) {
if (snap.exportVal()) {
pushData(path, snap.exportVal())
}
if (sendOk) {
sendOk = false
send({d: {r: requestId, b: {s: 'ok', d: {}}}, t: 'd'})
}
})
})
.catch(_log)
}
function handleUpdate (requestId, normalizedPath, fbRef, newData) {
var path = normalizedPath.path
_log('Client update ' + path)
newData = replaceServerTimestamp(newData)
var checkPermission = Promise.resolve(true)
if (server._ruleset) {
checkPermission = exportData(fbRef).then(function (currentData) {
var mergedData = _.assign(currentData, newData)
return tryWrite(requestId, path, fbRef, mergedData)
})
}
checkPermission.then(function () {
fbRef.update(newData)
send({d: {r: requestId, b: {s: 'ok', d: {}}}, t: 'd'})
}).catch(_log)
}
function handleSet (requestId, normalizedPath, fbRef, newData, hash) {
_log('Client set ' + normalizedPath.fullPath)
var progress = Promise.resolve(true)
var path = normalizedPath.path
newData = replaceServerTimestamp(newData)
if (normalizedPath.isPriorityPath) {
progress = exportData(fbRef).then(function (parentData) {
if (_.isObject(parentData)) {
parentData['.priority'] = newData
} else {
parentData = {
'.value': parentData,
'.priority': newData
}
}
newData = parentData
})
}
progress = progress.then(function () {
return tryWrite(requestId, path, fbRef, newData)
})
if (typeof hash !== 'undefined') {
progress = progress.then(function () {
return getSnap(fbRef)
}).then(function (snap) {
var calculatedHash = firebaseHash(snap.exportVal())
if (hash !== calculatedHash) {
pushData(path, snap.exportVal())
send({d: {r: requestId, b: {s: 'datastale', d: 'Transaction hash does not match'}}, t: 'd'})
throw new Error('Transaction hash does not match: ' + hash + ' !== ' + calculatedHash)
}
})
}
progress.then(function () {
fbRef.set(newData)
fbRef.once('value', function (snap) {
pushData(path, snap.exportVal())
send({d: {r: requestId, b: {s: 'ok', d: {}}}, t: 'd'})
})
}).catch(_log)
}
function handleAuth (requestId, credential) {
if (server._authSecret === credential) {
return send({t: 'd', d: {r: requestId, b: {s: 'ok', d: TokenValidator.normalize({ auth: null, admin: true, exp: null }) }}})
}
try {
var decoded = server._tokenValidator.decode(credential)
authToken = credential
send({t: 'd', d: {r: requestId, b: {s: 'ok', d: TokenValidator.normalize(decoded)}}})
} catch (e) {
send({t: 'd', d: {r: requestId, b: {s: 'invalid_token', d: 'Could not parse auth token.'}}})
}
}
function accumulateFrames (data) {
// Accumulate buffer until websocket frame is complete
if (typeof ws.frameBuffer === 'undefined') {
ws.frameBuffer = ''
}
try {
var parsed = JSON.parse(ws.frameBuffer + data)
ws.frameBuffer = ''
return parsed
} catch (e) {
ws.frameBuffer += data
}
return ''
}
ws.on('message', function (data) {
_log('Client message: ' + data)
if (data === 0) {
return
}
var parsed = accumulateFrames(data)
if (parsed && parsed.t === 'd') {
var path
if (typeof parsed.d.b.p !== 'undefined') {
path = parsed.d.b.p.substr(1)
}
path = normalizePath(path || '')
var requestId = parsed.d.r
var fbRef = path.path ? this.baseRef.child(path.path) : this.baseRef
if (parsed.d.a === 'l' || parsed.d.a === 'q') {
handleListen(requestId, path, fbRef)
}
if (parsed.d.a === 'm') {
handleUpdate(requestId, path, fbRef, parsed.d.b.d)
}
if (parsed.d.a === 'p') {
handleSet(requestId, path, fbRef, parsed.d.b.d, parsed.d.b.h)
}
if (parsed.d.a === 'auth' || parsed.d.a === 'gauth') {
handleAuth(requestId, parsed.d.b.cred)
}
}
}.bind(this))
send({d: {t: 'h', d: {ts: new Date().getTime(), v: '5', h: this.name, s: ''}}, t: 'c'})
},
setRules: function (rules) {
this._ruleset = new Ruleset(rules)
},
getData: function (ref) {
console.warn('FirebaseServer.getData() is deprecated! Please use FirebaseServer.getValue() instead') // eslint-disable-line no-console
var result = null
this.baseRef.once('value', function (snap) {
result = snap.val()
})
return result
},
getSnap: function (ref) {
return getSnap(ref || this.baseRef)
},
getValue: function (ref) {
return this.getSnap(ref).then(function (snap) {
return snap.val()
})
},
exportData: function (ref) {
return exportData(ref || this.baseRef)
},
close: function (callback) {
this._wss.close(callback)
},
setTime: function (newTime) {
this._clock.setTime(newTime)
},
setAuthSecret: function (newSecret) {
this._authSecret = newSecret
this._tokenValidator.setSecret(newSecret)
}
}
module.exports = FirebaseServer