Encoding an APNs token in JSON for node-apn (parse-server) - json

I've deployed a parse-server app in Heroku that I'd been developing locally using Docker. This app uses push notifications, and so needs access to some crypto data to play with APNs.
Locally I mounted a volume with the token key file in it. On Heroku this isn't an option, and I don't want to bundle the key in the package unencrypted. I've been trying to encode the token key in the JSON argument to the "PARSE_SERVER_PUSH" environment variable in different ways. It seems what's needed is a Buffer, but I have no idea how to represent such a thing in JSON, and I haven't found anything through some searching.
I'm currently using this at my push config:
{"ios":
{
"token": {
"key": {"type":"Buffer","data":[45, 45, ... 45]},
"keyId": "MYKEYID",
"teamId": "MYTEAMID"
},
"topic": "com.myApp",
"production": false
}
}
But the server chokes on the 'key' field:
2019-01-23T19:47:36.725181+00:00 app[web.1]: VError: Failed loading token key: path must be a string or Buffer
2019-01-23T19:47:36.725191+00:00 app[web.1]: at prepareToken (/parse-server/node_modules/apn/lib/credentials/token/prepare.js:15:13)
2019-01-23T19:47:36.725193+00:00 app[web.1]: at config (/parse-server/node_modules/apn/lib/config.js:43:31)
2019-01-23T19:47:36.725194+00:00 app[web.1]: at new Client (/parse-server/node_modules/apn/lib/client.js:21:19)
2019-01-23T19:47:36.725195+00:00 app[web.1]: at new Provider (/parse-server/node_modules/apn/lib/provider.js:12:19)
2019-01-23T19:47:36.725201+00:00 app[web.1]: at Function._createProvider (/parse-server/node_modules/#parse/push-adapter/lib/APNS.js:251:22)
2019-01-23T19:47:36.725203+00:00 app[web.1]: at new APNS (/parse-server/node_modules/#parse/push-adapter/lib/APNS.js:81:29)
2019-01-23T19:47:36.725204+00:00 app[web.1]: at new ParsePushAdapter (/parse-server/node_modules/#parse/push-adapter/lib/ParsePushAdapter.js:65:40)
2019-01-23T19:47:36.725205+00:00 app[web.1]: at loadAdapter (/parse-server/lib/Adapters/AdapterLoader.js:31:16)
2019-01-23T19:47:36.725206+00:00 app[web.1]: at loadAdapter (/parse-server/lib/Adapters/AdapterLoader.js:24:12)
2019-01-23T19:47:36.725207+00:00 app[web.1]: at getPushController (/parse-server/lib/Controllers/index.js:230:54)
Does anybody know how to achieve this?
EDIT: The documentation (https://github.com/node-apn/node-apn/blob/master/doc/provider.markdown) suggests it's possible:
token.key {Buffer|String} The filename of the provider token key (as
supplied by Apple) to load from disk, or a Buffer/String containing
the key data.

Related

NodeJS - MySQL server not working after some time

Basically I have my Node.js server working along with MySQL. When I work on my localhost everything's fine. The connection to my local DB (I'm using XAMPPP) is great and nothing breaks.
The problem comes along when the server is hosted by a provider. The one I hired uses cPanel and everithing's great until some time passes, because I get this error:
events.js:377
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:209:20)
Emitted 'error' event on Connection instance at:
at Connection._handleProtocolError (/home/adminis6/Artesofa/node_modules/mysql/lib/Connection.js:423:8)
at Protocol.emit (events.js:400:28)
at Protocol._delegateError (/home/adminis6/Artesofa/node_modules/mysql/lib/protocol/Protocol.js:398:10)
at Protocol.handleNetworkError (/home/adminis6/Artesofa/node_modules/mysql/lib/protocol/Protocol.js:371:10)
at Connection._handleNetworkError (/home/adminis6/Artesofa/node_modules/mysql/lib/Connection.js:418:18)
at Socket.emit (events.js:400:28)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
errno: -104,
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! amor-muebles#1.0.0 start: `node app.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the amor-muebles#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/adminis6/.npm/_logs/2021-11-30T19_15_37_322Z-debug.log
I've been researching how to solve this problem and the only useful answer I got basically said that the DB connection was timming out, so all I had to do was to make a request on an interval and hope it won't break. So I wrote the following code in my app.js file:
const fetch = require("node-fetch");
setInterval(() => {
fetch('sample-endpoint');
}, 30000);
Although this seemed to have solved my problem, it appeared over and over again (note that the server did last longer being up).
Later on, some people taught me about CRONS so I made the following CRON:
PATH=$PATH:$HOME/bin; export PATH; /usr/bin/pgrep "node" >/dev/null || (cd /home/adminis6/Artesofa/; pkill node; pkill npm; nohup npm start &)
And it does work, because it gets the server up, but it instantly crashes (literally right after the server initiates, even after the server connects to the DB successfully), and it logs the following:
> amor-muebles#1.0.0 start /home/adminis6/Artesofa
> node app.js
Server running on port 3100
mysql connected
events.js:377
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:209:20)
Emitted 'error' event on Connection instance at:
at Connection._handleProtocolError (/home/adminis6/Artesofa/node_modules/mysql/lib/Connection.js:423:8)
at Protocol.emit (events.js:400:28)
at Protocol._delegateError (/home/adminis6/Artesofa/node_modules/mysql/lib/protocol/Protocol.js:398:10)
at Protocol.handleNetworkError (/home/adminis6/Artesofa/node_modules/mysql/lib/protocol/Protocol.js:371:10)
at Connection._handleNetworkError (/home/adminis6/Artesofa/node_modules/mysql/lib/Connection.js:418:18)
at Socket.emit (events.js:400:28)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
errno: -104,
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! amor-muebles#1.0.0 start: `node app.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the amor-muebles#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/adminis6/.npm/_logs/2021-11-30T20_14_02_182Z-debug.log
I don't know what else to try nor I have much more time, please help!
If you need it, here is my app.js:
/* ----------- Server initialization ----------- */
//Here are all the modudule's require
const app = express();
// Connect to mySQL DB
const db = require('./db/connectDB');
// Set server to listen on specified port
app.listen(process.env.PORT || '4000', () => {
console.log(`Server running on port ${process.env.PORT} AAAAA`);
})
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.set('views', [
path.join(__dirname, 'views/adminSite/')
]);
/* ----------- Middleware ----------- */
app.use(express.urlencoded({ extended: true }));
app.use(helmet());
app.use(cookieParser());
app.use(morgan('tiny'));
/* ----------- Routes ----------- */
app.use('/api', apiRoutes);
setInterval(() => {
fetch('https://administracionartesofa.com/api/sucursales');
}, 30000);
And, finally, here is my connectDB file:
const mysql = require('mysql');
const dotenv = require('dotenv').config();
const settings = process.env.ENV === 'dev' ? require('./devSettings.json') : require('./prodSettings.json');
let db;
const connectDatabase = () => {
if (!db) {
db = mysql.createConnection(settings);
db.connect((err) => {
if (err) {
console.log('Database error');
console.log(err);
connectDatabase();
} else {
console.log('mysql connected');
}
})
}
return db;
}
module.exports = connectDatabase();
Use a mysql connection pool in your nodejs program. Your hosting provider's cheap and nasty shared MySql server has an aggressively short idle connection time limit. If you hold open a connection for too long the server slams it shut, so you get ECONNRESET.
Why? Cybercreeps trying to break in to random servers on the internet for fun and profit. This slows them down a bit, hopefully.
Connection pools cope with this behind the scenes if you
set up a pool at app startup, and
grab a connection from the pool when you need one, use it, and then return it to the pool.
Or, you can skip the pooling and just close your connection when you're done using it, then open a new one when you need it again. That will work fine for a low-volume app, but it might cause some inefficient connection thrashing if your volume goes up. Pools are better.

Launching Chromium from Puppeteer is timing out on a certain machine - TimeoutError: waiting for target failed: timeout 30000ms exceeded

I am getting the below error when running Puppeteer and launching Chromium. Also, Chromium opens up as crashed page. I am unable to navigate to any URL from the window that opens up.
Surprisingly, I get this error only when running from a certain machine (in my corporate network). When running from another machine in my corporate network as well as my laptop, it works fine.
Upon looking around, I noticed the recommendation to add ignoreDefaultArgs: [ '--disable-extensions' ] } to the config, which I did, but still receive the same error. Would you have any recommendation on what I am missing?
The error message is as follows
LOG >> -- START PUPPY --
(node:12008) UnhandledPromiseRejectionWarning: TimeoutError: waiting for target failed: timeout 30000ms exceeded
at Object.waitWithTimeout (C:\Users\afhassan\Puppy\node_modules\puppeteer\lib\cjs\puppeteer\common\helper.js:224:26)
at Browser.waitForTarget (C:\Users\afhassan\Puppy\node_modules\puppeteer\lib\cjs\puppeteer\common\Browser.js:269:45)
at ChromeLauncher.launch (C:\Users\afhassan\Puppy\node_modules\puppeteer\lib\cjs\puppeteer\node\Launcher.js:100:27)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:12008) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12008) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
The error is caused by this line
this._browser = await launch(CONFIG.launchOptions);
launch is imported from Puppeteer
import {
Browser,
Page,
launch,
CDPSession
} from 'puppeteer';
My config is as follows
{ verbose: true,
launchOptions: { headless: false },
defaultViewPort: { width: 1920, height: 1080 },
domain: 'domain.com',
mySiteDomain: 'domain.com',
users:
{ admin:
{ username: 'myusername',
password: 'mypassword' },
user0:
{ username: 'myusername',
password: 'mypassword' } },
tests: [ 'NameOfTest' ],
ignoreDefaultArgs: [ '--disable-extensions' ] }
The relevant parts of my package.json is as follows
"dependencies": {
"puppeteer": "^5.5.0",
"yargs": "^15.4.1"
},
"devDependencies": {
"#types/puppeteer": "^5.4.2",
"#types/yargs": "^15.0.11",
"babel-cli": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
}

Error when migrating database using edeliver

I've always used edeliver to deploy my apps, but on my new app, I'm getting a weird error.
When I run mix edeliver migrate production, I'm getting this response:
EDELIVER MYPROJECT WITH MIGRATE COMMAND
-----> migrateing production servers
production node:
user : user
host : example.com
path : /home/user/app_release
response: RPC to 'myproject#127.0.0.1' failed: {'EXIT',
{#{'__exception__' => true,
'__struct__' =>
'Elixir.ArgumentError',
message => <<"argument error">>},
[{ets,lookup_element,
['Elixir.Ecto.Registry',nil,3],
[]},
{'Elixir.Ecto.Registry',lookup,1,
[{file,"lib/ecto/registry.ex"},
{line,18}]},
{'Elixir.Ecto.Adapters.SQL',sql_call,
6,
[{file,"lib/ecto/adapters/sql.ex"},
{line,251}]},
{'Elixir.Ecto.Adapters.SQL','query!',
5,
[{file,"lib/ecto/adapters/sql.ex"},
{line,198}]},
{'Elixir.Ecto.Adapters.MySQL',
'-execute_ddl/3-fun-0-',4,
[{file,"lib/ecto/adapters/mysql.ex"},
{line,107}]},
{'Elixir.Enum',
'-reduce/3-lists^foldl/2-0-',3,
[{file,"lib/enum.ex"},{line,1826}]},
{'Elixir.Ecto.Adapters.MySQL',
execute_ddl,3,
[{file,"lib/ecto/adapters/mysql.ex"},
{line,107}]},
{'Elixir.Ecto.Migrator',
'-migrated_versions/2-fun-0-',2,
[{file,"lib/ecto/migrator.ex"},
{line,44}]}]}}
But when I type mix edeliver restart production followed by the migration command, everything goes normally. Why is this happening?

Cannot create JHipster application (error in ng plugin)

I appreciate this is probably not a JHipster specific issue, but how some of my dependencies may be installed. It happens on 3.0.0 and 3.1.0. On the other hand 2.27.0 is fine.
This happens when I run yo jhipster.
...
Server app generated successfully.
Client app generated successfully.
(node:38364) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
[21:00:11] Using gulpfile ~/dev/projects/blog/gulpfile.js
[21:00:11] Starting 'install'...
[21:00:11] Starting 'wiredep:test'...
[21:00:11] Starting 'wiredep:app'...
[21:00:11] Starting 'ngconstant:dev'...
[21:00:11] 'ngconstant:dev' errored after 12 ms
[21:00:11] Error in plugin 'gulp-tslint-log'
TypeError: Path must be a string. Received null
at assertPath (path.js:7:11)
at Object.dirname (path.js:1324:5)
at getFilePath (/Users/me/dev/projects/blog/node_modules/gulp-ng-constant-fork/index.js:95:27)
at DestroyableTransform.objectStream [as _transform] (/Users/alberto/dev/projects/blog/node_modules/gulp-ng-constant-fork/index.js:60:25)
at DestroyableTransform.Transform._read (/Users/alberto/dev/projects/blog/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:184:10)
at DestroyableTransform.Transform._write (/Users/alberto/dev/projects/blog/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:172:12)
at doWrite (/Users/alberto/dev/projects/blog/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:237:10)
at writeOrBuffer (/Users/alberto/dev/projects/blog/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:227:5)
at DestroyableTransform.Writable.write (/Users/alberto/dev/projects/blog/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:194:11)
at DestroyableTransform.Writable.end (/Users/alberto/dev/projects/blog/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:352:10)
at ngConstantPlugin (/Users/alberto/dev/projects/blog/node_modules/gulp-ng-constant-fork/index.js:33:16)
at Gulp.<anonymous> (/Users/alberto/dev/projects/blog/gulpfile.js:164:12)
at module.exports (/Users/alberto/dev/projects/blog/node_modules/orchestrator/lib/runTask.js:34:7)
at Gulp.Orchestrator._runTask (/Users/alberto/dev/projects/blog/node_modules/orchestrator/index.js:273:3)
at Gulp.Orchestrator._runStep (/Users/alberto/dev/projects/blog/node_modules/orchestrator/index.js:214:10)
at Gulp.Orchestrator.start (/Users/alberto/dev/projects/blog/node_modules/orchestrator/index.js:134:8)
Then when I start the application I get this on the browser's console:
Uncaught Error: [$injector:modulerr] Failed to instantiate module blogApp due to:
Error: [$injector:nomod] Module 'blogApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.5.2/$injector/nomod?p0=badgeritoApp
at http://127.0.0.1:8080/bower_components/angular/angular.js:68:12
at http://127.0.0.1:8080/bower_components/angular/angular.js:2034:17
at ensure (http://127.0.0.1:8080/bower_components/angular/angular.js:1958:38)
at module (http://127.0.0.1:8080/bower_components/angular/angular.js:2032:14)
at http://127.0.0.1:8080/bower_components/angular/angular.js:4524:22
at forEach (http://127.0.0.1:8080/bower_components/angular/angular.js:321:20)
at loadModules (http://127.0.0.1:8080/bower_components/angular/angular.js:4508:5)
at createInjector (http://127.0.0.1:8080/bower_components/angular/angular.js:4430:19)
at doBootstrap (http://127.0.0.1:8080/bower_components/angular/angular.js:1710:20)
at bootstrap (http://127.0.0.1:8080/bower_components/angular/angular.js:1731:12)
Here is the content of .yo-rc.json
{
"generator-jhipster": {
"jhipsterVersion": "3.0.0",
"baseName": "blog",
"packageName": "com.albertofaci.blog",
"packageFolder": "com/albertofaci/blog",
"serverPort": "8080",
"authenticationType": "session",
"hibernateCache": "no",
"clusteredHttpSession": "no",
"websocket": "no",
"databaseType": "mongodb",
"devDatabaseType": "mongodb",
"prodDatabaseType": "mongodb",
"searchEngine": "no",
"buildTool": "gradle",
"enableSocialSignIn": false,
"rememberMeKey": "94cf21b11aff8d8d4a9b9b3724834876b995e5b1",
"useSass": false,
"applicationType": "monolith",
"testFrameworks": [
"gatling"
],
"enableTranslation": true,
"nativeLanguage": "en",
"languages": [
"en",
"es"
]
}}
node version: v6.0.0
npm version: 3.8.7
java 8
Any hints or ideas?
I had exactly the same problem as the OP, I changed to use the LTS version of Node as Gaƫl Marziou suggested. This fixed the problem.

OS X, Elixir, Ecto, Crypto, MySQL

Trying out Elixir & Ecto (not Phoenix) in a sample app to help me learn the language.
Running my program results in the following error:
=INFO REPORT==== 7-Apr-2016::16:23:28 ===
application: logger
exited: stopped
type: temporary
** (Mix) Could not start application tpos: exited in: Tpos.start(:normal, [])
** (EXIT) exited in: GenServer.call(#PID<0.164.0>, {:get_all, Tpos.Data.Models.ProfitCenter}, 5000)
** (EXIT) exited in: GenServer.call(#PID<0.163.0>, {:checkout, :run}, 5000)
** (EXIT) exited in: GenServer.call(#PID<0.168.0>, {:connect, [hostname: "localhost", timeout: 5000, otp_app: :tpos, repo: Tpos.Repo, adapter: Ecto.Adapters.MySQL, database: "tpos", username: "tpos", password: "tpos", port: 3306]}, 5000)
** (EXIT) an exception was raised:
** (UndefinedFunctionError) undefined function :crypto.hash/2 (module :crypto is not available)
(crypto) :crypto.hash(:sha, "tpos")
(mariaex) lib/mariaex/protocol.ex:150: Mariaex.Protocol.mysql_native_password/2
(mariaex) lib/mariaex/protocol.ex:47: Mariaex.Protocol.dispatch/2
(mariaex) lib/mariaex/connection.ex:284: Mariaex.Connection.process/2
(mariaex) lib/mariaex/connection.ex:251: Mariaex.Connection.handle_info/2
(stdlib) gen_server.erl:615: :gen_server.try_dispatch/4
(stdlib) gen_server.erl:681: :gen_server.handle_msg/5
(stdlib) proc_lib.erl:240: :proc_lib.init_p_do_apply/3
If I do a mix deps.clean --all and a mix.deps get and run the program again, it works. But only once. If I exit and attempt to run it again, I receive the above error.
The line that causes the error is:
data = Repo.all(ProfitCenter)
As I said, the first time through this runs fine and returns the expected data. It's only on subsequent runs that the error pops up.
From mix.exs:
defmodule Tpos.Mixfile do
use Mix.Project
def project do
[app: :tpos,
version: "0.0.1",
elixir: "~> 1.2",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps]
end
def application do
[ applications: [:mariaex, :ecto],
mod: { Tpos, [] } ]
end
defp deps do
[
{:credo, "~> 0.3", only: [:dev, :test]},
{:mariaex, "~> 0.5.0"},
{:ecto, "~> 1.1.5"},
{:exactor, "~> 2.2.0"}
]
end
end
I'm running OS X 10.11.1, and have tried several things to get it going based on advice like this.
Thoughts? Thanks!
The error states that you don't have :crypto module. You can verify that by running:
iex(1)> Application.start(:crypto)
:ok
If you get anything else than :ok, it means that your Erlang installation is not fully functional. It happens very often when you install Erlang via kerl. Kerl doesn't consider lack of openssl an error. It just skips crytpo libraries without warning.
To install fully functional Erlang with kerl you need to run:
brew install openssl
brew install unixodbc
After that create ~/.kerlrc file with following contents:
KERL_INSTALL_MANPAGES=yes
KERL_CONFIGURE_OPTIONS="--disable-hipe --enable-smp-support --enable-threads
--enable-kernel-poll --with-wx
--with-ssl=/usr/local/opt/openssl
--with-odbc=/usr/local/opt/unixodbc"
And try to reinstall Erlang. This config also adds wx-widgets which are handy if you want to run :observer application. Unixodbc also may come in handy, but less often.
If you are using different tool to install Erlang, you still need to point it to openssl path during compilation.
Alternatively, you can use packages provided by Erlang Solutions: https://www.erlang-solutions.com/resources/download.html They should install all required dependencies including crypto.