Push notification send fails on server with 401 error - firefox-os

I am developing KaiOS application with web push notification capability.
While following code works on Chrome and current Mozilla it fails on KaiOS.
NodeJS code:
const push = require('web-push');
const vapidKeys = {
publicKey: 'PUBLIC_KEY',
privateKey: 'PRIVATE_KEY',
};
push.setVapidDetails(
'valid#email.com',
vapidKeys.publicKey,
vapidKeys.privateKey
);
const pushSub = {
endpoint: 'https://push.kaiostech.com:8443/wpush/v2/gAAAAABgNqjxZulGGFU',
keys: {
auth: 'AUTH',
p256dh: 'P256dH',
},
};
KaiOS:
failed to send notification WebPushError: Received unexpected response code
at IncomingMessage.<anonymous> (/node_modules/web-push/src/web-push-lib.js:347:20)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
statusCode: 401,
headers: {
date: 'Thu, 25 Feb 2021 15:35:19 GMT',
'content-length': '15',
'content-type': 'text/plain; charset=utf-8',
connection: 'close'
},
body: '{"errno":"109"}',
endpoint: 'https://push.kaiostech.com:8443/wpush/v2/gAAAAABgNqjxZulGGFU-72vZJFv0avzqAZAdWd7FSwZBINZ8AvsEkxAU2J3AFcs0e4aEUIYxi8aSzCCn8ihUgof_nfLGyR8VBprtzgZEABf14rSb9RgGgwxQip6f2792pS0BcUawcerZbNstCotDYTXdNZ7jQvegfDHUEHvril1KeEeaMoi4nGk'
}
But on Mozilla (with appropriate key changes) it response is successful. Same on Chrome.
notification response: {
statusCode: 201,
body: '',
headers: {
'access-control-allow-headers': 'content-encoding,encryption,crypto-key,ttl,encryption-key,content-type,authorization',
'access-control-allow-methods': 'POST',
'access-control-allow-origin': '*',
'access-control-expose-headers': 'location,www-authenticate',
'content-type': 'text/html; charset=UTF-8',
date: 'Wed, 24 Feb 2021 20:38:35 GMT',
location: 'https://updates.push.services.mozilla.com/m/gAAAAABgNrlLgRnDfpaVmZjc6eqnAxoXkaYkTT4nKCTI1ZIBt62hfu2l3XvGr0F8HfvW54etByCQNSX89ubyBjd2VtXOTPqfsiC4-iDBWol9q9GRwiBSgjFc2M5-avDmrRpq9eCAsxlgGCzp2sRYRqvVDAQBHa8GznLzKmDE87rWZM6ItMiLS8PN0jqiSZFYMlqooeCK53QN',
server: 'nginx',
'strict-transport-security': 'max-age=31536000;includeSubDomains',
ttl: '2419200',
'content-length': '0',
connection: 'Close'
}
}
Here is client service worker code:
self.addEventListener('push', (event) => {
console.log('push event', event);
const title = event.data.text();
event.waitUntil(self.registration.showNotification(title));
});
Any ideas, what could be a problem?

push.sendNotification(pushSub, 'hello my name is me', {
contentEncoding: 'aesgcm'
})
.then(function (res) {
console.log('notification response: ', res);
})
.catch(function (err) {
console.error('failed to send notification', err);
});
https://github.com/web-push-libs/web-push/issues/603

This server push.kaiostech.com require authorization. It allows access from KaiOS device only.

Related

Node https request returns Missing or duplicate parameters

Trying to get a token from ADP's API.
const https = require('https')
const fs = require('fs')
require('dotenv').config()
var requestBody = JSON.stringify({
client_id: process.env.ADP_CLIENT_ID,
client_secret: process.env.ADP_CLIENT_SECRET,
grant_type: 'client_credentials',
});
const options = {
hostname: 'accounts.adp.com',
port: 443,
path: '/auth/oauth/v2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': requestBody.length
},
cert: fs.readFileSync('certificate.pem'),
key: fs.readFileSync('private.key'),
agent: false,
}
console.debug(options)
const req = https.request(options, (res) => {
let response = ''
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (chunk) => {
response += chunk
})
res.on('end', ()=>{
console.log('Body: ', JSON.parse(response));
})
}).on("error", (err) => {
console.error("Error: ", err.message);
});
req.write(requestBody)
req.end()
When the script runs, an error is returned from the service:
$ node ./get_token.js
{
hostname: 'accounts.adp.com',
port: 443,
path: '/auth/oauth/v2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': 141
},
cert: <Buffer ... bytes>,
key: <Buffer ... bytes>,
agent: false
}
statusCode: 400
headers: {
'adp-correlationid': 'XXX',
'x-ca-err': '3003103',
'cache-control': 'no-store',
pragma: 'no-cache',
'content-type': 'application/json;charset=UTF-8',
'content-length': '84',
date: 'Wed, 18 Jan 2023 17:50:06 GMT',
connection: 'close',
server: 'ADP API'
}
body: {
error: 'invalid_request',
error_description: 'Missing or duplicate parameters'
}
What am I missing or duplicating?
I needed to correctly serialize the requestBody:
...
const qs = require('querystring');
...
var requestBody = qs.stringify({
client_id: process.env.ADP_CLIENT_ID,
client_secret: process.env.ADP_CLIENT_SECRET,
grant_type: 'client_credentials',
});
which generated the expected response:
{
access_token: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
token_type: 'Bearer',
expires_in: 3600,
scope: 'api'
}

Why Stripe Payment System is not working?

i have implemented a payment system with stripe but when i connect with server then the server is crashed. Please answer the problem. I have created this code for payment system for my website.
My client site code-
useEffect(() => {
fetch('http://localhost:5000/create-payment-intent', {
method: 'POST',
headers: {
'content-type': 'application/json',
authorization: `Bearer ${localStorage.getItem('accessToken')}`
},
body: JSON.stringify({ price })
})
.then(res => res.json())
.then(data => {
console.log(data);
if (data?.clientSecret) {
setClientSecret(data.clientSecret);
}
})
}, [clientSecret, price])
my server site code-
app.post('/create-payment-intent', verifyJWT, async (req, res) => {
const service = req.body;
const price = service.price;
amount = price * 100;
const paymentIntent = await stripe.paymentIntents.create({
amount: amount,
currency: 'us',
payment_method_types: ['card']
});
res.send({ clientSecret: paymentIntent.client_secret })
})
error is coming-
rawType: 'invalid_request_error',
code: 'parameter_invalid_integer',
doc_url: 'https://stripe.com/docs/error-codes/parameter-invalid-integer',
param: 'amount',
detail: undefined,
headers: {
server: 'nginx',
date: 'Sun, 24 Jul 2022 12:43:34 GMT',
'content-type': 'application/json',
'content-length': '240',
connection: 'keep-alive',
'access-control-allow-credentials': 'true',
'access-control-allow-methods': 'GET, POST, HEAD, OPTIONS, DELETE',
'access-control-allow-origin': '*',
'access-control-expose-headers': 'Request-Id, Stripe-Manage-Version, X-Stripe-External-Auth-Required, X-Stripe-Privileged-Session-Required',
'access-control-max-age': '300',
'cache-control': 'no-cache, no-store',
'idempotency-key': 'f17b3002-4ad7-4765-9442-3395630c3c3b',
'original-request': 'req_7sXCHThynqnGhE',
'request-id': 'req_7sXCHThynqnGhE',
'stripe-version': '2020-08-27',
'strict-transport-security': 'max-age=31556926; includeSubDomains; preload'
},
From the error message, it means that the amount sent in the PaymentIntent Create request was not an integer.
I'd suggest logging into Stripe dashboard and search the request ID req_7sXCHThynqnGhE in the search bar at the top to check amount value that you sent to Stripe.
Apart from amount value, the currency value in the request was also incorrect. It should be a three-letter ISO currency code in lowercase such as "usd".

Can't get access token by call Meteor HTTP get request

Http token request description(Doc)
URL: https://demo.tld/connect/token
HTTP Verb: POST
HTTP Headers:
Authorization: Basic base64encode(clientId:clientSecret)
Content-Type: multipart/form-data
HTTP Body:
grant_type: client_credentials
My requested code:
try {
let endCodeOfAuth = 'Basic ' + new Buffer(clientId + ':' + clientSecret).toString('base64');
HTTP.post("https://demo.tld/connect/token", {
headers: {
'Authorization': endCodeOfAuth,
'Content-Type': 'multipart/form-data'
},
content: 'grant_type:client_credentials'
}, (error, res) => {
if (res) console.log("2. res", res );
else console.log("1. error", error);
});
return true;
} catch (error) {
return false;
}
Response:
statusCode: 500,
content: '',
headers: {
server: 'Kestrel',
'x-powered-by': 'ASP.NET',
date: 'Mon, 01 Jun 2020 11:54:59 GMT',
connection: 'close',
'content-length': '0'
},
data: null
}

Why is res.header() not working in express?

I am trying to authenticate a user for login. However, I don't manage to send a response header.
Login function
// POST /users/login
router.post('/users/login', async (req, res) => {
try {
const body = _.pick(req.body, ['email', 'password']);
const user = await User.findByCredentials(body.email, body.password);
const token = await user.generateAuthToken();
req.session['token'] = 'Bearer ' + token;
req.session['user'] = user;
// the following line does not seem to work properly
res.header('Authorization', 'Bearer ' + token).send(user);
} catch (err) {
res.status(401).json({ message: "Nutzerdaten sind nicht korrekt" });
}
});
Axios plugin
$axios.onResponse(res => {
console.log(res.headers) // does not return an authorization header
if (res.headers.authorization) {
store.commit('auth/SET_TOKEN', res.headers.authorization)
}
return res
})
console.log(res.headers)
'x-powered-by': 'Express',
vary: 'Origin',
'access-control-allow-credentials': 'true',
'content-type': 'application/json; charset=utf-8',
'content-length': '2',
etag: 'W/"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w"',
date: 'Tue, 30 Jul 2019 12:35:00 GMT',
connection: 'keep-alive'
I would be very thankful for any kind of help!

FCM legacy API call responded with JSON_PARSING_ERROR: Unexpected token END OF FILE at position 0

I am trying to implement the legacy call to FCM server where the response is unexpected. There it shows the Parsing Error which is not traceable for me as of now. I am posting the code snippet below. Please help me out if anything is missing or coded in wrong manner.
var request = require('request');
let message = {
"to": atoken,
"data": {
title: "My first push notification",
body: "Hello World!!!"
}
};
// //let message = req.body.message;
let key = "AIzaSyA1zIxVFJ3F7-_-XXXXXXXXXXXXXXXXXXX";
request({
method: 'POST',
uri: 'https://fcm.googleapis.com/fcm/send',
headers: {
'Content-type': 'application/json',
'Authorization': 'key=' + key
},
postData: JSON.stringify(message)
},
function (error, response, body) {
if (error) {
console.error('upload failed:', error);
res.status(500).json({ error: true, data: { message: error.message } });
} else {
let data = response;
console.log('Upload successful! Server responded with:',
data.toJSON());
//res.status(200).json(response);
}
});
The response coming is:
body:
'JSON_PARSING_ERROR: Unexpected token END OF FILE at position 0.\n',
headers:
{ 'content-type': 'text/plain; charset=UTF-8',
date: 'Tue, 16 Apr 2019 06:34:05 GMT',
expires: 'Tue, 16 Apr 2019 06:34:05 GMT',
'cache-control': 'private, max-age=0',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '1; mode=block',
server: 'GSE',
'alt-svc': 'quic=":443"; ma=2592000; v="46,44,43,39"',
'accept-ranges': 'none',
vary: 'Accept-Encoding',
connection: 'close' },
request:
{ uri:
Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'fcm.googleapis.com',
port: 443,
hostname: 'fcm.googleapis.com',
hash: null,
search: null,
query: null,
pathname: '/fcm/send',
path: '/fcm/send',
href: 'https://fcm.googleapis.com/fcm/send' },
method: 'POST',
headers:
{ 'Content-type': 'application/json',
Authorization: 'key=AIzaSyA1zIxVFJ3F7-_-hrIbTHTehNRmTUwG8Z0',
'content-length': 0 } } }
Try changing postData: JSON.stringify(message) in request.post() to body: JSON.stringify(message).

Resources