GithubHelp home page GithubHelp logo

urish / firebase-server Goto Github PK

View Code? Open in Web Editor NEW
675.0 26.0 92.0 663 KB

Firebase Realtime Database Server Implementation

JavaScript 6.23% TypeScript 93.77%
firebase-server server-socket javascript firebase firebase-database testing-tools typescript database

firebase-server's Introduction

Project Deprecated!

This project has reached its end-of-life, and will no longer be maintained. For information about the official alternative from the Firebase team, have a look at the Firebase Local Emulators Migration Guide.

Moving forward, new features will not be added, and only security-related bugfixes will be released.

firebase-server

Firebase Web Socket Protocol Server. Useful for emulating the Firebase server in tests.

Copyright (C) 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, Uri Shaked and contributors

Build Status Coverage Status npm version

Installation

You can install firebase-server through npm:

npm install --save-dev firebase-server

or yarn:

yarn add -D firebase-server

Usage examples

const FirebaseServer = require('firebase-server');

new FirebaseServer(5000, 'localhost', {
  states: {
    CA: 'California',
    AL: 'Alabama',
    KY: 'Kentucky'
  }
});

After running this server, you can create a Firebase client instance that connects to it:

import * as firebase from 'firebase/app';
import 'firebase/database';

const app = firebase.initializeApp({
  databaseURL: `ws://localhost:5000`,
});

app.database().ref().on('value', (snap) => {
  console.log('Got value: ', snap.val());
});

Setup with global test hooks

In the case of Mocha, you'd do something like the example below.

// => e.g. global-test-hooks.js
const FirebaseServer = require("firebase-server");

let firebaseServer;

before(() => {
   firebaseServer = new FirebaseServer(5000, "localhost");
});

after(async () => {
   await firebaseServer.close();
});
// => require the file with the --file flag
mocha --file /path/to/global-test-hooks.js

Command Line Interface

This package installs a CLI script called firebase-server. It can be installed locally or globally. If installed locally, use the following path to start the server: ./node_modules/.bin/firebase-server

The following command will start a firebase server on port 5555:

firebase-server -p 5555

... and with a specified bind IP address:

firebase-server -p 5555 -a 0.0.0.0

To bootstrap the server with some data you can use the -d,--data or the -f,--file option. Note: The file option will override the data option.

firebase-server -d '{"foo": "bar"}'

firebase-server -f ./path/to/data.json

To load Firebase Security rules upon startup you can use the -r,--rules option.

firebase-server -r ./path/to/rules.json

You can also specify a shared client auth token secret with the -s argument:

firebase-server -s some-shared-secret

To enable REST API, run:

firebase-server -e

Note: currently REST API does not implement authentication or authorization.

To daemonize the server process, use:

firebase-server -b

To write the PID to a file, use:

firebase-server --pid /var/run/firebase-server.pid

_Note: PID file can be written with or without daemonization, and is NOT written by default when daemonizing.

For more information, run:

firebase-server -h

FirebaseServer methods

The constructor signature is FirebaseServer(portOrOptions, name, data) where portOrOptions is either a port number or a WebSocket.Server options object with either port or server set. name is optional and is just used to report the server name to clients. data is the initial contents of the database.

If you want the server to pick a free port for you, simply use the value 0 for the port. You can then get the assigned port number by calling the getPort() method on the returned server object.

FirebaseServer instances have the following API:

  • close(): Promise - Stops the server (closes the server socket)
  • getValue() - Returns a promise that will be resolved with the current data on the server
  • exportData() - Returns a promise that will be resolved with the current data on the server, including priority values. This is similar to DataSnapshot.exportVal().
  • address() - Returns the address the server is listening on
  • port(): number - Returns the port number the server is listening on
  • setRules(rules) - Sets the security rules for the server. Uses the targaryen library for rule validation.
  • setAuthSecret(secret) - Sets the shared secret used for validating Custom Authentication Tokens.
  • setTime(timestamp) - Sets the server time. The server time is returned by ServerValue.TIMESTAMP and is also used for checking the validity of Custom Authentication Tokens.

Debug logging

This project uses the excellent debug module for logging. It is configured by setting an environment variable:

$ DEBUG=* mocha                                # log everything
$ DEBUG=firebase-server* mocha                 # log everything from firebase-server
$ DEBUG=firebase-server:token-generator mocha  # log output from specific submodule

Advanced options are available from the debug docs

License

Released under the terms of MIT License:

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

firebase-server's People

Contributors

abhishekgahlot avatar azell avatar bmcbarron avatar dchaley avatar dependabot[bot] avatar dotdoom avatar dylanjha avatar gomorizsolt avatar ibash avatar jamestalmage avatar jamiemchale avatar jperasmus avatar kirkov avatar loayg avatar mediavrog avatar mironal avatar nfarina avatar nirrek avatar p avatar p-salido avatar robertrossmann avatar rybit avatar samtstern avatar tommie avatar urish avatar wyattisimo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebase-server's Issues

`createClient()` method

A convenience method to quickly create a client Firebase connected to the current server.

A sketch of the proposed solution:

createClient: function() {
    var fbUrl = 'ws://localhost:' + this.port;
    var oldProto = String.prototype.split;
    var Firebase = firebaseCopy();
    var host = url.parse(fbUrl).host;
    String.prototype.split = function () {
        if (this === host) {
            return ['localhost', 'firebaseio', 'test'];
        } else {
            return oldProto.apply(this, arguments);
        }
    };
    var result = new Firebase(fbUrl);
    String.prototype.split = oldProto;
    return result;
}

The string prototype trickery overcomes the internal checks in the client library, so we can safely use localhost as the target hostname. Hopefully, we will get some support for this from the official library, and will be able to remove this prototyping hacking.

test.firebase.localhost as host causes error

Your instructions to use test.firebase.localhost causes the Firebase node module to throw an error. Specifically:

Error: FIREBASE FATAL ERROR: test.firebase.localhost:5000 is no longer supported.
Please use <YOUR FIREBASE>.firebaseio.com instead

If you use test.firebaseio.com instead, then it works as intended.

Modules I am using:

"firebase": "^2.2.7",
"firebase-server": "^0.1.1"

API Key is invalid on tests with Karma + Jasmine

Hi,

I'm struggling to use firebase-server with Karma + Jasmine.

I have a web app made with AngularJS, in my app.js I make something like this:

angular.module('siteAdminApp', [
    'config',
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch',
    'ngTagsInput',
    'ngMask',
    'ngImgCrop',
    'ngFileUpload',
    'ngMessages',
    'firebase',
    'firebase.ref',
    'firebase.auth',
    'firebase.time',
    'ui.select',
    'ui.sortable',
    'ui.bootstrap',
    'mgcrea.ngStrap',
    'ui.utils.masks',
    'translate'
  ])
  .config(['CONF', '$windowProvider', function (CONF, $windowProvider) {
    // Workaround to make tests work and avoid get multiple instances of Firebase on tests
    var $window = $windowProvider.$get();
    try {
      $window.firebaseApp = $window.firebase.app('myapp');
    } catch (err) {
      $window.firebaseApp = $window.firebase.initializeApp(CONF.firebase.config, 'myapp');
    }
  }]);

CONF is a factory which returns the Firebase 3 configuration with databaseURL, apiKey, etc...

I'm using "browserify" with Karma, to be able to load modules to my tests, so my test looks like:

'use strict';

var FirebaseServer = require('firebase-server');

describe('Any test', function () {

  var server = new FirebaseServer(5555, 'ws://127.0.1', {});

  it('Testing', function (done) {
    done();
  });

});

I already made other tests work using firebase-server running by command line and then running tests.

But now I'm trying not do do this, but use FirebaseServer inside my tests, and with that scenario I'm getting that error:

Error: Your API key is invalid, please check you have copied it correctly. in /var/folders/06/m9yhsng108ndr6tlrncl0lpc0000gn/T/7363266c7b7f8c1d39ccc00c08e1be9f.browserify (line 61882)
    xm@/var/folders/06/m9yhsng108ndr6tlrncl0lpc0000gn/T/7363266c7b7f8c1d39ccc00c08e1be9f.browserify:61882:634 <- node_modules/firebase/firebase.js:298:0
    /var/folders/06/m9yhsng108ndr6tlrncl0lpc0000gn/T/7363266c7b7f8c1d39ccc00c08e1be9f.browserify:61903:359 <- node_modules/firebase/firebase.js:319:0
    R@/var/folders/06/m9yhsng108ndr6tlrncl0lpc0000gn/T/7363266c7b7f8c1d39ccc00c08e1be9f.browserify:61609:94 <- node_modules/firebase/firebase.js:25:0
    [native code]
    /var/folders/06/m9yhsng108ndr6tlrncl0lpc0000gn/T/7363266c7b7f8c1d39ccc00c08e1be9f.browserify:61904:88 <- node_modules/firebase/firebase.js:320:0
    /var/folders/06/m9yhsng108ndr6tlrncl0lpc0000gn/T/7363266c7b7f8c1d39ccc00c08e1be9f.browserify:61606:273 <- node_modules/firebase/firebase.js:22:0
    forEach@[native code]
    initializeApp@/var/folders/06/m9yhsng108ndr6tlrncl0lpc0000gn/T/7363266c7b7f8c1d39ccc00c08e1be9f.browserify:61606:252 <- node_modules/firebase/firebase.js:22:0
    Fire/Users/thiago/Documents/Projects/Sheeper/sheeper-webServer@http://localhost:8080/var/folders/06/m9yhsng108ndr6tlrncl0lpc0000gn/T/7363266c7b7f8c1d39ccc00c08e1be9f.browserify:38960:35 <- node_modules/firebase-server/index.js:79:0

So, I know firebase-server is just starting to support Firebase 3.

What I need to know is, is there a way to make this work? Or is better I keep going with command line to run my tests?

Nested security rules not being processed

First of all - awesome project.

I have stumbled over this problem. When I define security rules that are nested e.g.

{
"rules":
{
".read" : " auth.service==true ",
".write" : " auth.service==true ",

"organisations": 
{
  "$uid": 
  {
    ".read"  : "true",
    ".write" : "(auth!=null && data.val() == null) || (newData.child('id') == data.child('id'))"
  }
}

}
}

The rules in the lowest level are not processed by Firebase-Server in tests but are processed when Targaryen is called in tests directly. Is this an issue or am I doing something wrong?

Thanks

Wire protocol does not match Firebase server

With debug logging turned on:

Firebase
Sun Aug 16 23:32:08 PDT 2015 [DEBUG] WebSocket: ws_1 - handleIncomingFrame complete frame: {d={r=1, b={s=ok, d={}}}, t=d}
Sun Aug 16 23:32:08 PDT 2015 [DEBUG] Connection: conn_1 - received data message: {r=1, b={s=ok, d={}}}

firebase-server
Sun Aug 16 23:15:19 PDT 2015 [DEBUG] WebSocket: ws_0 - handleIncomingFrame complete frame: {d={r=1, b={s=ok, d=}}, t=d}
Sun Aug 16 23:15:19 PDT 2015 [DEBUG] Connection: conn_0 - received data message: {r=1, b={s=ok, d=}}

I believe that "d" should be an empty hash instead of the empty string.

goOffline is not a function

I'm getting this error as the firebase dependency of the firebase-copy library is being downloaded on its last version causing an issue when calling that method on line 50 of firebase-server/index.js.

Verison 2.3.1 was:
Firebase.goOffline()
Now is:
Firebase.database().goOffline()

Cheers!

25 Specs Fail with firebase 3.3.0

Nice tests! I ran into some issues and found that it's because recent firebase clients don't work with firebase-server. Running the test suite with firebase 3.3.0 has 25 specs failing with the message

Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

This matches the behavior I'm seeing with my project were the real firebase will call callbacks and resolve promises where firebase-server does not.

Any ideas?

Mocha results

  #firebaseHash
    ✓ should return empty hash string for null values
    ✓ should return correct hash for boolean true
    ✓ should return correct hash for boolean false
    ✓ should return correct hash for numeric values
    ✓ should return correct hash for string values
    ✓ should return correct hash for objects with a single key
    ✓ should return correct hash for objects with a multiple keys
    ✓ should return correct hash for primitive value with a numeric priority
    ✓ should return correct hash for primitive value a string priority
    ✓ should return correct hash for objects with a numeric priority
    ✓ should return correct hash for objects with a string priority

  Firebase Server
    1) should successfully accept a client connection
    2) should accept initial data as the third constructor parameter
    3) should return the correct value for child nodes
    #update
      4) should update the given child
      5) should support `firebase.database.ServerValue.TIMESTAMP` values
    #set
      6) should update server data after calling `set()` from a client
      7) should combine websocket frame chunks
      8) should support `firebase.database.ServerValue.TIMESTAMP` values
    #remove
      9) should remove the child
      10) should trigger a "value" event with null
    #transaction
      11) should save new data to the given location
      12) should return existing data inside the updateFunction function
      13) should successfully handle transactions for object nodes that have priority
      14) should successfully handle transactions for primitive nodes that have priority
      15) should not update the data on server if the transaction was aborted
    security rules
      16) should forbid reading data when there is no read permission
      17) should forbid writing when there is no write permission
      18) should forbid updates when there is no write permission
      19) should use custom token to deny read
      20) should use custom token to allow read
    #setPriority
      21) should update the priority value for the given child
    #setWithPriority
      22) should update both the value and the priority value for the given child
    server priority
      23) should be reflected when calling snapshot.exportVal() on client
    FirebaseServer.getData()
      24) should synchronously return the most up-to-date server data
    FirebaseServer.close()
      ✓ should call the callback when closed
    FirebaseServer.setAuthSecret()
      25) should accept raw secret when handling admin authentication
      - should reject invalid auth requests with raw secret

  testable-clock
    ✓ should be of type `function`
    ✓ should lock to a static time if set to a number
    ✓ should accept a function that returns the current time
    ✓ should proxy another clock
    ✓ should default to the system time
    ✓ should throw if provided bad input

  token-validator
    ✓ #decode should decode a valid token
    ✓ #decode should include token options (e.g. iat, notBefore, expires) in decoded token
    ✓ #normalize should convert `nbf` and `exp` to longer form names
    ✓ #decode should throw if token has a bad signature
    ✓ should accept a custom clock function
    ✓ #withTime should create a new token-validator with a different testable-clock
    ✓ should not validate the signature (i.e. allow any signer), if secret is not set


  25 passing (50s)
  1 pending
  25 failing

Update callback is never called

I'm using the latest Firebase Node SDK in conjunction with firebase-server. If I use the update function with an onComplete callback, that callback is never called.

This is only happening for update. Set and remove are both calling their onComplete callbacks.

If I attach a value listener to the node I'm updating, I can indeed see that the update is taking place.

$loaded() and $save() does not work in Karma unit tests

Hi,

I'm facing some problems to write on firebase-server using AngularFire, could anyone help me?

Here is my UsernameService:

angular.module('siteAdminApp')
.factory('UsernameService', ['$firebaseObject', '$window', '$timeout','Ref', 'FBURL', 'Utils',
function ($firebaseObject, $window, $timeout, Ref, FBURL, Utils) {

            var ref = null;

            return {
                $sync: function (username) {
                    return $firebaseObject(Ref.child('bindings/username').child(username));
                },
                $ref: function () {
                    if (!ref) {
                        ref = new $window.Firebase(FBURL + '/bindings/username');
                    }
                    return ref;
                },
                $get: function (username, onsuccess, onfail) {
                    this.$ref().child(username).once('value', function (snap) {
                        if (snap.val()) {
                            onsuccess(snap.val());
                        } else {
                            onfail();
                        }
                 });
                },
                $save: function (userKey, user, onsuccess, onfail) {
                    var obj = this.$sync(user.username);
                    console.log('antes de carregar');
                    obj.$loaded().then(function () {
                        console.log('depois de carregar');
                        obj.$value = {
                            'uid': userKey,
                            'email': Utils.encodeEmail(user.email),
                            'provider': user.provider
                        };
                        obj.$save().then(onsuccess).catch(onfail);
                    }).catch(onfail);
                }
            };
        }]);

And here is my UsernameServiceTest:

'use strict';

describe('Service: UsernameService', function () {

  var ref, UsernameService, $timeout, $httpBackend, $rootScope;

  var bobmarley = {
    'uid': 'aaabbbccc',
    'email': 'bobmarley@gmail,com',
    'provider': 'password'
  };

  var maryjane = {
    'uid': 'dddeeefff',
    'email': 'maryjane@gmail,com',
    'provider': 'password'
  };

  // load the module
  beforeEach(module('siteAdminApp'));

  // inject services
  beforeEach(inject(function (_UsernameService_, _$timeout_, _$httpBackend_, _$rootScope_) {
    UsernameService = _UsernameService_;
    $timeout = _$timeout_;
    $httpBackend = _$httpBackend_;
    $rootScope = _$rootScope_;
  }));

  // create scenario
  beforeEach(function (done) {
    // Workaround to the error: Error: Unexpected request: GET views/main.html
    // Found at: http://stackoverflow.com/a/28226651/3542459
    $httpBackend.whenGET(/\.html$/).respond('');

    ref = UsernameService.$ref().child('bobmarley');
    ref.set(bobmarley, done);
  });

  it('should get username "bobmarley"', function (done) {
    UsernameService.$get('bobmarley',
      function (data) {
        expect(data).toEqual(bobmarley);
        done();
      },
      function () {
        expect(false).toBe(true);
        done();
      });
  });

  it('should save username "maryjane"', function (done) {
    UsernameService.$save('dddeeefff', {
        'firstName': 'Mary',
        'lastName': 'Jane',
        'email': '[email protected]',
        'username': 'maryjane',
        'provider': 'password'
      },
      function (data) {
        expect(data).toEqual(maryjane);
        done();
      },
      function () {
        expect(false).toBe(true);
        done();
      });

    $rootScope.$apply();
  });
});

I'm using:

angular: 1.4.9
firebase": 2.2.2
angularfire: 1.0.0

My problem is: the $get() works fine, but the $save() never returns. I put some logs and $loaded() never returns the promise also.

I saw this issue here: #41

So I tried $rootScope.$apply(), but doesn't work either.

I tried $timeout.flush() and $httpBackend.flush() also, without success.

I'm 3 days trying to test this service and the write never worked unfortunately, even with MockFirebase.

Can anyone help me?

Frame size of websocket if bigger sent into segment gives error.

Hi,

I liked this repo but if the frame size is bigger than what firebase allows. It throws error because json parsing is not possible. I can raise the PR for accumulating buffer until parsing of frame is successful. Looking forward to hear your thoughts.

Redirect requests to real database

My company developed an app called U-Report (https://goo.gl/6YuyGW) using firebase. U-Report is a partnership between Ilhasoft and Unicef. It’s a tool that really makes the difference in the people life.

We’re deploying the U-Report platform on Syria and they are having problems( using our app. They can’t make login or share their stories, respond polls or anything else that request a connection to Firebase. Syria government or the Google itself blocks Firebase requests.

@urish: Is there any way​ using this library to host a firebase server on Amazon (it’s available on Syria) that only redirects the requests to Firebase and respond to clients?

Support ServerValue.TIMESTAMP

#15 implements testable-clock. We should use that to allow statically / programmatically assigned timestamps instead of using the system time (which makes writing tests harder).

Server won't connect if no default data provided

When I start up the server like this, everything is fine:

var FirebaseServer = require('firebase-server');
new FirebaseServer(5000, 'test.firebaseio.com', {
    states: {
        CA: 'California',
        AL: 'Alabama',
        KY: 'Kentucky'
    }
});

But if I do not pass sample data, I get WebSocket connection errors when I try to connect:

var FirebaseServer = require('firebase-server');
new FirebaseServer(5000, 'test.firebaseio.com');
// WebSocket connection to 'ws://test.firebaseio.com:5000/.ws?v=5' failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED

Script using Firebase Server won't end.

I am using the latest version from npm, and running the basic example from docs.

var FirebaseServer = require('firebase-server')
var Firebase = require('firebase')

const instance = new FirebaseServer(5000, 'test.firebaseio.localhost', {
    states: {
        CA: 'California',
        AL: 'Alabama',
        KY: 'Kentucky'
    }
});

var client = new Firebase('ws://test.firebaseio.localhost:5000');
client.once('value', function(snap) {
    console.log('Got value: ', snap.val());
});

I even tried calling instance.close and instance._wss.close() explicitly. But the script still keeps hanging. Do you have some hanging listener left?

Node version v4.4.2 and v5.11.0

Can't get data from swift app / Can't connect from Android

I'm connecting to firebase-server from a swift app and I can't get any data.

This is my server config:

var FirebaseServer = require('firebase-server');

new FirebaseServer(5000, 'test.firebase.localhost', {
   states: {
        CA: 'California',
        AL: 'Alabama',
        KY: 'Kentucky'
    }
});

I'm running the firebase server in debug mode, so when the app starts I see the connection on the terminal and the message sent with all the data on the states path:

firebase-server New connection from 127.0.0.1:52221 +11s
  firebase-server Sending message: {"d":{"t":"h","d":{"ts":1468957827447,"v":"5","h":"test.firebase.localhost","s":""}},"t":"c"} +0ms
  firebase-server Client message: {"t":"d","d":{"r":1,"a":"s","b":{"c":{"sdk.objc.3-0-1":1}}}} +2ms
  firebase-server Client message: {"t":"d","d":{"r":2,"a":"q","b":{"p":"\/states","h":""}}} +0ms
  firebase-server Client listen states +0ms
  firebase-server Sending message: {"d":{"a":"d","b":{"p":"states","d":{"AL":"Alabama","CA":"California","KY":"Kentucky"},"t":null}},"t":"d"} +1ms
  firebase-server Sending message: {"d":{"r":2,"b":{"s":"ok","d":{}}},"t":"d"} +1ms

This is the swift listener. I always get null:

let ref = FIRDatabase.database().reference().child("states")
ref.observeEventType(.Value) { (snap) in
      print(snap.value)
 }
Optional(<null>)

On Android I can't even connect to the firebase-server.

Could you help me please? Thanks!

WebSocket connection to 'ws://test.firebaseio.com:5000/.ws?v=5' failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED

This may just be me holding it wrong:
Connecting to the local firebase_server works fine from the nodejs client, but fails with the error above in the browser (Chromium Version 43.0.2357.130 Ubuntu 14.04 (64-bit)).

Firebase browser client version: 2.2.9
Firebase node client version: 2.2.7
Firebase-server version: 0.3.0

Firebase server:

var FirebaseServer = require('firebase-server');
var fs = require('fs');
var data = JSON.parse(fs.readFileSync('firebase_data.json', 'utf-8'));
FirebaseServer.enableLogging(true);
new FirebaseServer(5000, 'test.firebaseio.com', data);

/etc/hosts:

127.0.0.1       test.firebaseio.com

Firebase browser client:

new Firebase('ws://test.firebaseio.com:5000')

Error, every second in the Chrome console:

WebSocket connection to 'ws://test.firebaseio.com:5000/.ws?v=5' failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED
Firebase server debug output
[firebase-server] Listening for connections on port 5000

As I mentioned, the connection from node works fine. Debug output:

[firebase-server] New connection from 127.0.0.1:54567
...

Any idea?

Transactions fail for nodes with priority value

Reproducing test case:

it('should successfully handle transactions for nodes that have priority', function (done) {
    server = new FirebaseServer(PORT, 'localhost:' + PORT, {
        '.priority': 500,
        doge: 'such transaction'
    });
    var client = new Firebase(newServerUrl());

    client.transaction(function (currentData) {
        return 'very priority';
    }, function (error, committed, snapshot) {
        assert.equal(error, null);
        assert.equal(committed, true);
        assert.deepEqual(snapshot.val(), 'very priority');
        done();
    });
});

Is firebase server agnostic to the version of the client firebase library being used?

The firebase production database works with either the 2.x sdks or the 3.x sdks.

Ideally, this firebase-server package should behave similarly. It shouldn't care which version of the firebase client library is being used.

However, it appears that this package is dependent on a particular firebase version. For example:
https://github.com/urish/firebase-server/blob/master/index.js#L73 firebase.initializeApp will only work if the 3.x sdk is being used.

Is there a way this could be made the work with both version of firebase client libraries? Or specify in the README the most up-to-date version for 2.x (I think it would be 0.5.4)

Implement firebase REST Api

This would be good for when developing backend code that will eventually talk to the real firebase servers via the REST api.

this.Firebase.goOffline is not a function

I'm seeing this error when I start firebase server. At first glance this appears to be an error indicating that I am running the new version of the firebase client library (3.0).

I investigated further and found out that in my regular node_modules/ folder in my project directory I have installed firebase 2.4.2, which is my intention.

However, when I dig into node_modules/firebase-sever/node_modules I found that firebase-server had installed firebase 3.0.3 incorrectly as one of its dependencies.

TypeError: this.Firebase.goOffline is not a function
at Object.FirebaseServer (/Users/dylanjhaveri/code/crowdcast/node_modules/firebase-server/index.js:50:16)

packages in my project package.json

    "firebase": "2.4.2",
    "firebase-server": "0.5.4",

packages in package.json located at node_modules/firebase-server/package.json

  "dependencies": {
    "cli": "^0.11.1",
    "debug": "^2.2.0",
    "firebase-copy": "0.2.0",
    "jwt-simple": "^0.3.1",
    "lodash": "3.10.1",
    "native-or-bluebird": "1.2.0",
    "targaryen": "2.0.0",
    "ws": "0.8.1"
  },

when I look at the folders inside node_modules/firebase-server/node_modules/ I see:

cli/
debug/
firebase/            <<<<  where is this coming from?
firebase-copy/
jwt-simple/
lodash/
native-or-bluebird/
targaryen/
ws/

Standalone file

I'm trying to run the server like so

// server.js
var FirebaseServer = require('firebase-server');
new FirebaseServer(5000, 'localhost:5000');

Then calling node server.js. Is this supported? The connection looks like this:

// app.js
var app = new Firebase('ws://local.firebaseio.com:5000');

I ask because when my app connects to that firebase I am receiving the following error:

WebSocket connection to 'ws://local.firebaseio.com:5000/.ws?v=5' failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED
15firebase.js:175 WebSocket connection to 'ws://local.firebaseio.com:5000/.ws?v=5' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

I have the follwoing in my hosts file:

127.0.0.1 local.firebaseio.com

And ping shows that it is working.

$ ping local.firebaseio.com
PING local.firebaseio.com (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.071 ms
64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.061 ms
64 bytes from localhost (127.0.0.1): icmp_seq=3 ttl=64 time=0.061 ms

$ ping prod.firebaseio.com
PING prod.firebaseio.com (104.197.110.104) 56(84) bytes of data.
64 bytes from 104.110.197.104.bc.googleusercontent.com (104.197.110.104): icmp_seq=1 ttl=43 time=180 ms
64 bytes from 104.110.197.104.bc.googleusercontent.com (104.197.110.104): icmp_seq=2 ttl=43 time=182 ms
64 bytes from 104.110.197.104.bc.googleusercontent.com (104.197.110.104): icmp_seq=3 ttl=43 time=179 ms

Bluebird warning when using with NODE_ENV='development'

Warning: a promise was created in a handler but was not returned from it
    at new A (eval at <anonymous> (/.../node_modules/firebase-server/node_modules/firebase-copy/index.js:7:14), <anonymous>:31:1337)
    at X.set (eval at <anonymous> (/.../node_modules/firebase-server/node_modules/firebase-copy/index.js:7:14), <anonymous>:259:322)
    at /.../node_modules/firebase-server/index.js:227:11
    at processImmediate [as _immediateCallback] (timers.js:383:17)
From previous event:
    at handleSet (/.../node_modules/firebase-server/index.js:226:13)
    at Object.<anonymous> (/.../node_modules/firebase-server/index.js:289:6)
    at emitTwo (events.js:87:13)
    at WebSocket.emit (events.js:172:7)
    at Receiver.ontext (/.../node_modules/firebase-server/node_modules/ws/lib/WebSocket.js:816:10)
    at /.../node_modules/firebase-server/node_modules/ws/lib/Receiver.js:477:18
    at Receiver.applyExtensions (/.../node_modules/firebase-server/node_modules/ws/lib/Receiver.js:364:5)
    at /.../node_modules/firebase-server/node_modules/ws/lib/Receiver.js:466:14
    at Receiver.flush (/.../node_modules/firebase-server/node_modules/ws/lib/Receiver.js:340:3)
    at Receiver.opcodes.1.finish (/.../node_modules/firebase-server/node_modules/ws/lib/Receiver.js:482:12)
    at Receiver.<anonymous> (/.../node_modules/firebase-server/node_modules/ws/lib/Receiver.js:451:33)
    at Receiver.add (/.../node_modules/firebase-server/node_modules/ws/lib/Receiver.js:95:24)
    at Socket.realHandler (/.../node_modules/firebase-server/node_modules/ws/lib/WebSocket.js:800:20)
    at emitOne (events.js:77:13)
    at Socket.emit (events.js:169:7)
    at readableAddChunk (_stream_readable.js:153:18)
    at Socket.Readable.push (_stream_readable.js:111:10)
    at TCP.onread (net.js:531:20)

Is this a mistake in the project?

Add ws close callback

0.8.1 of ws adds a callback to the close method. It would be useful for firebase-server to allow the passing through of a callback.

Examples of usage would be at the end of a test spec waiting for the server to close and the port to free up before moving on the next spec that might require that port to be free.

If people are happy with this I can make the quick modification and bump the ws version in package.json?

Process never terminates.

The process never terminates despite calling close, whose callback executes but there appear to be active handles still listening.

var FirebaseServer, server;
FirebaseServer = require('firebase-server');
server = new FirebaseServer(5000, 'localhost.firebaseio.test', {});

server.close(function() {
  console.log('closed');
  require('active-handles').print();
});

How to test auth?

I'd like to test my auth related code for Firebase 3 using firebase-server. Does firebase-server somehow support Firebase Admin SDK? Or is there any way to setup accounts in firebase-server? Thanks.

Hack websocket implementation to provide synchronous/flushable communication

Since we have open source access to faye-websocket, and since firebase-copy provides a way to hook require calls, we might be able to emulate some of the synchronous flush goodness from mockfirebase.

var server = new FirebaseServer(port, name, ...);

var Firebase = server.createSynchronousClient(); // uses firebase-copy and a custom facade for `faye-websocket`

var ref = new Firebase(url); // maybe throw if they try to point it anywhere but our server

ref.on('value', function (snap) {
  assert(...);
});

server.flush(); // synchronously flush communications.

While it might be a significant undertaking, synchronous methods are so much easier to test, and the model has been proven extremely useful on other projects (angular's ngMock $timeout.flush()).

Upgrade Required

I just tried to follow your readme, however I only see a blank page saying: "Upgrade Required". I checked, but I use the latest available version via npm. What am I doing wrong?

Create Contributing.md

Sections:

  • Instructions for cloning / building / testing
  • List of build targets
  • Roadmap of desired features. reference github issue tracker
  • Conditions for an accepted PR (passing tests, etc).
  • Recommend open an issue before starting work
  • Hints for reverse engineering production firebase: see here and here.

Switch to a zero-config style standard.

I think xo is probably the closest match to the existing style (1 tab, semicolons). I use xo on most of my new projects, as I found I generally can do what I want with the fewest number of eslint-disable-line comments.

standard is probably the most common, but would require significant modification of existing code (2 spaces, no semicolons).

Remove triggers two value events

Using a value listener on a node that's being removed triggers the callback twice. The first time with an empty snapshot and a second time with the pre-deletion snapshot.

var FirebaseServer = require('firebase-server');
var s = new FirebaseServer(5000, 'dummy.firebaseio.test', {
    states: {
        CA: 'California',
        AL: 'Alabama',
        KY: 'Kentucky'
    }
});

var Firebase = require('firebase');
var client = new Firebase('ws://dummy.firebaseio.test:5000');

// Attaching a value listener to states/CA
client.child('states').child('CA').on('value', function(snap) {
    console.log('Value: ' + snap.val());
});

// After 1 second, remove states/CA
setTimeout(function() {
    console.log('Removing CA');
    client.child('states').child('CA').remove();
}, 1000);

Output:

Value: California
Removing CA
Value: null
Value: California

Remaining TODO's from #15

Originally posted in #15, but that is closed, reposting here so we don't lose track.

Mirror Server Error Responses for authWithCustomToken in the following Scenarios

(current thought is not to pursue these)

  • Invalid JWT - it is not a valid JWT token
  • Invalid Signature - wrong secret
  • Too Early - the server time is before notBefore
  • Too Late - the server time is after expires
  • No uid property - firebase-token-generator the docs say you are required to provide a uid as part of authData. That is a firebase specific requirement (it will not be validated by a generic JWT library like jwt-simple).
  • No iat property - I do not actually know if this is required, but firebase-token-generator automatically adds it (it is the time the token was created).

Mirror Server Action as Token Reaches Expiration

We need to figure out what happens when a token expires.

  • Are you just switched to "unauthenticated" mode?
  • Is a message sent to idle clients?
  • How is ref.onAuth() triggered as your token expires?

Additional Items / Housekeeping

  • Update documentation
  • more descriptive methods: setSecret => setAuthSecret
  • option to disable expires / notBefore checks
  • option to disable token signature check (setSecret(null))

Firebase 3.x

I see from the readme files that the Firebase 2.x api is being used. Does the server support the 3.x api or are there plans to do that? Thanks

npm install error

Hi everyone.
First i ll like to thanks for such a proyect. I have a problem and i don't have any clue. I using windows 10 with the nodejs version 6.9.1 and npm version 3.10.8. I don't know why but i think i cant get all the dependencies instaled. After run de command:
$npm install --save-dev firebase-server
and
$\node_modules.bin\firebase-server
i get the error:
Error: Cannot find module 'firebase'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object. (C:\Users\israel\Documents\Dev\Firebase\firebase-server-master\node_modules\firebase-server\index.js:17:16)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)

Any help?
thanks

documentation needed for using with firebase 3.0.0

This is a super cool project, and I'd really like to use it, but I'm using firebase 3 and the README doesn't explain what support is available for firebase 3.0.0 or how to do anything with it. The top questions for me right now are how do you initialize the app and what kinds of authentication can I use firebase-server to test?

Angularfire synchronized array

Hi,

Do you think there is anything special that would make firebase-server not work with $firebaseArray?
I have the following array:

var arr = $firebaseArray(firebaseRoot.child('users/id123/matches'))
arr.$loaded().then(function(){console.log('loaded')})

the data does get sent by firebase-server, since I get the debug output:

 firebase-server Client listen users/id123/matches +0ms
  firebase-server Sending message: {"d":{"a":"d","b":{"p":"users/id123/matches","d":{"matchId1":{"people":{"id345":"Firstname"},"tags":{"tag":true}}},"t":null}},"t":"d"} +3ms
  firebase-server Sending message: {"d":{"r":4,"b":{"s":"ok","d":{}}},"t":"d"} +1ms

But the $loaded promise never gets resolved. $firebaseArray is just a wrapper around the usual firebase methods, so I can't quite understand why that would be - any idea?

How should i use getValue()?

I have this code:

var item = fbClient.database().ref('tests').push();
item.set({
    'test': 'update server'
})
.then(function (err) {
    assert.deepEqual(fbServer.getData().tests[item.key], {
        'test': 'update server'
    });
    assert.deepEqual(fbServer.getValue('tests/' + item.key), {
        'test': 'update server'
    });
});

The first assert works, but the second not. Both getValue() and exportData() always returns null.

Value callbacks always triggered with null first

If I listen for the value event on a node, the snapshot that's returned contains no data on the first event. So if I'm using once, the value is null. But if I use on, the callback is called twice, once with null and once again with the data.

var FirebaseServer = require('firebase-server');

var s = new FirebaseServer(5000, 'dummy.firebaseio.test', {
    states: {
        CA: 'California',
        AL: 'Alabama',
        KY: 'Kentucky'
    }
});

var Firebase = require('firebase');

var client = new Firebase('ws://dummy.firebaseio.test:5000');

client.child('states').child('CA').on('value', function(snap) {
    console.log('Value: ' + snap.val());
});

Output:

Value: null
Value: California

Using in iOS (Swift) app

Hello, the server is running all right on my laptop and javascript code can write and read data. However, when trying to access from Swift code is crashing. I have not researched well, just a quick research if somebody has made it work with Firebase Swift (Pod). thanks!

Not working with [email protected]

You probably guessed this already, but wanted to track it somewhere. The new Firebase release includes some big changes to how the library is initialized - instead of using a constructor, they have moved to a "global initialization" strategy. So new Firebase(...) is no longer valid. This may also impact the way firebase-server uses an internal instance of the Firebase client itself to perform some tasks.

substr of undefined

It seems that there is a strong assumption that all firebase requests be of the form:

{"t":"d","d":{"r":4,"a":"q","b":{"p":"/accounts","h":""}}}

However, when using the emberfire library, the firebase-server crashes immediately on the first request.

The culprit seems to be this message, which is sent by the library before the first actual request.

{"t":"d","d":{"r":1,"a":"s","b":{"c":{"sdk.js.0-0-0":1}}}}

No idea what this request does, but the message payload does not have a property d.b.p

Which causes problems in index.js - line 53

var path = parsed.d.b.p.substr(1);

p is undefined, and the server crashes.

I find a workaround by using the following code change:

var path; if (parsed.d.b.p) { path = parsed.d.b.p.substr(1); }

The code is defensive about testing the path variable for a truthy value a few lines later, so this fix doesn't seem to cause any issues. Should I create a pull request, or do you have another suggestion?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.