socket io client return disconnected - websocket

i want to make an automated chat in the app https://play.google.com/store/apps/details?id=io.anonchat
and ran into websocket
fiddler screen
i try it and another combinations, but cant connect
const socket = io.connect('https://anonchatapi.stivisto.com',
{query: {
version:'3.9.1',
language:'ru',
platform:'android',
deviceInfo:'samsung SM-G977N',
systemInfo:'Android 5.1.1',
cookie:'3bfa4edc-3c99-48d5-ba9c-2305b7771994',
secret:'U2FsdGVkX1+RTHTFXotg1jNhp9UdCyGoq4GNYmjRiNXgamGNXrjaXuoa23PJtIHRnlP+xRtXut6Rdbz1bCkm+N/MAYSIB2FDTdkYxReFDzE=',
},
transports: ['websocket'],
extraHeaders: {
'Cookie': '__cfduid=d8c5c875e657a6996f040fdbefb81525a1609957302; __cflb=0H28vwUUvyk1WC5Cn8KUkUHh5BL9vWCsQL4m3TepR29; io=1pOXWig4qOhPEbceAJDA',
'origin': 'https://anonchatapi.stivisto.com',
'Upgrade': 'websocket',
'Connection': 'Upgrade',
'Sec-WebSocket-Key': 'K1OkajjYjq9nJS7oHoQUwg==',
'Sec-WebSocket-Version': 13,
'Host': 'anonchatapi.stivisto.com',
'Accept-Encoding': 'gzip',
'User-Agent': 'okhttp/3.12.1'
}
});
console.log(socket.open())
socket.on('connect', () => {
console.log('EEEE!')
});
request in fiddler
Cookie: __cfduid=d8c5c875e657a6996f040fdbefb81525a1609957302; __cflb=0H28vwUUvyk1WC5Cn8KUkUHh5BL9vWCsQL4m3TepR29; io=1pOXWig4qOhPEbceAJDA
origin: https://anonchatapi.stivisto.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: K1OkajjYjq9nJS7oHoQUwg==
Sec-WebSocket-Version: 13
Host: anonchatapi.stivisto.com
Accept-Encoding: gzip
User-Agent: okhttp/3.12.1
websocket screen
431[null,{"user":{"uid":"b4957eb5-2145-46b5-ae79-94b10f7a9f26","exploreDialogId":"5ff6354c84624f424b8ea28b","createdAt":"2021-01-06T18:21:43.107Z","lastUpdatedAt":"2021-01-06T22:17:55.002Z","language":"ru","ban":null,"hasPremium":false,"searchPreferences":{"male":false,"female":false},"settings":{"public":{"gender":"female","username":"","aboutMe":"","showPremiumStatus":false,"profilePicture":null},"pushNotifications":{"newMessage":{"sounds":true,"show":true},"dialog":{"sounds":true,"show":true},"like":{"sounds":true,"show":true}}},"token":"fIDquK0QlSo:APA91bHV6z_s58aWewbVxS9fugMbaPNp0krEO1h9_z7R48csM5Q9Z0Eq80IpF_aQUzqOiE_60l0Nj4NkOWSTEEh6mHMH2mtaTAG2-Erm8Tw3UrLXlzyf5lwlD5Qru-0RFM__9Z93cYtr"}}]
how me need make it work?

socket.io lib dont suport latest node version.
v14.15.4 work good
const io = require('socket.io-client');
const debug = require('debug');
debug.enable('socket.io-client');
const socket = io.connect('https://anonchatapi.stivisto.com',
{
query: {
version: '3.9.1',
language: 'ru',
platform: 'android',
deviceInfo: 'samsung SM-G977N',
systemInfo: 'Android 5.1.1',
cookie: '3bfa4edc-3c99-48d5-ba9c-2305b7771994',
secret: 'U2FsdGVkX1+RTHTFXotg1jNhp9UdCyGoq4GNYmjRiNXgamGNXrjaXuoa23PJtIHRnlP+xRtXut6Rdbz1bCkm+N/MAYSIB2FDTdkYxReFDzE=',
},
transports: ['websocket']
});
socket.connect();
socket.on('connect', () => {
console.log('EEEE!')
});

Related

Why i can't attach authorization to header in apollo client? (Nestjs, Graphql, Apollo)

I'm trying to bind frontend user registration and authorization to my Nestjs/Graphql server. The functionality of creation and authorization works, I create a user and put an access token in the cookie. But the problem is that I can't navigate through closed endpoints because Apollo doesn't allow me to attach the token to the request headers.
My server on backend (main.ts):
async function bootstrap() {
const app = await NestFactory.create(AppModule, { cors: true });
app.useGlobalPipes(new ValidationPipe())
app.useGlobalGuards(new JwtAuthGuard(new Reflector()))
app.enableCors({
origin: 'http://localhost:3000',
credentials: true,
allowedHeaders: 'Origin,X-Requested-With,Content-Type,Accept,Authorization,authorization'
})
await app.listen(3001);
}
bootstrap();
Graphql module in AppModule:
GraphQLModule.forRoot({
autoSchemaFile: join(process.cwd(), 'src/schema/gql'),
sortSchema: true,
driver: ApolloDriver
})
Apollo client on a frontend:
import { parseCookies } from 'nookies'
import { setContext } from '#apollo/client/link/context';
import { ApolloClient, InMemoryCache, createHttpLink } from '#apollo/client'
const cookies = parseCookies()
const httpLink = createHttpLink({
uri: 'http://localhost:3001/graphql'
});
const authLink = setContext((_, { headers }) => {
const token = cookies.access_token
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
export const client = new ApolloClient({
cache: new InMemoryCache(),
credentials: 'same-origin',
link: authLink.concat(httpLink)
})
My Rrequest Headers:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
Cache-Control: max-age=0
Connection: keep-alive
Cookie: access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVxMUBnbWFpbC5jb20iLCJzdWIiOjUsImlhdCI6MTY1NzM2NTI2OSwiZXhwIjoxNjU3MzY4ODY5fQ.AdbThqNQl746P-T653jkpvdKXTdrVOsj0SUsjzoTQDo
DNT: 1
Host: localhost:3000
Referer: http://localhost:3000/playlists
sec-ch-ua: ".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: same-origin
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36
The reason why your setup doesn't work is probably because HttpOnly is set to true for your cookies and therefore aren't accessible through the JavaScript Document.cookie API. So your authLink doesn't have any effect. So, if you want to include it in the headers you either set HttpOnly to false, which is not preferred, or you store the token in LocaleStorage after authentication.
However as the cookies are set by your server, you can just make sure the cookies are send over to the server, by including credentials within your requests. The credentials however should be set within createHttpLink instead of ApolloClient.
But:
your graphql server is running at port 3001,
your frontend app is served through port 3000.
So credentials : same-origin won't include the headers, as different ports are different origins. Set credentials to include, instead of same-origin. On the server, the token can be accessed through the request.cookies instead of the http-headers. You don't need to parseCookies on the client side.

Fetch request headers vs. Postman headers

Using Postman I'm able to do the following call:
GET https://tickets.ramdom.com/api/events/95
Request Headers
Host: tickets.ramdom.com
Cookie: OptanonConsent=isIABGlobal=false
Cache-Control: no-cache
Postman-Token: db42ad48-62f1-4e3f-8903-66002116e8a3
The call works fine. Now I want to reproduce the same call using fetch and Firefox console.
So I create the following piece of code:
const opts = {
headers: {
Host: 'tickets.ramdom.com',
Cookie: 'OptanonConsent=isIABGlobal=false'
}
};
fetch('hhttps://tickets.ramdom.com/api/events/95', opts)
.then((response) => {
alert(response)
})
.catch((error) => {
alert(error)
});
But I always get the following error:
TypeError: NetworkError when attempting to fetch resource.
Do you know what I'm doing wrong?
Thanks

Getting error when returning list from rest service admin-on-rest

I'm getting the following error on my first admin component.
uncaught at handleFetch TypeError: newRecords.reduce is not a function
When I attempt to query my rest-api. I'm using the majority of the supplied simple rest client with some additional security headers thrown in.
My response from my API is:
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Content-Range: Account 0-0/1
Server: Kestrel
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Content-Range
Request-Context: appId=cid-v1:9f32da6c-a0dd-445f-b59f-d5d01ee6c462
X-AA-Request-ID: ad76be2b-0a29-4179-8fab-6ac0b83e411b
X-SourceFiles: =?UTF-8?B?RTpcRGV2XEFBSHViXEFBLkh1Yi5TZXR0aW5ncy5TZXJ2aWNlXEFBLkh1Yi5TZXR0aW5ncy5TZXJ2aWNlXGFwaVx2MVxhY2NvdW50?=
X-Powered-By: ASP.NET
Date: Tue, 15 Aug 2017 02:56:56 GMT
The body of the response has:
{"data":[{"changeManagements":[],"serviceProfiles":[],"id":1,"login":"cuken","permissionLevel":9001,"note":"This is a dev test user"}],"totalItems":1}
EDIT
Here is the fetch.js file I modified from the simple rest client example:
import HttpError from './HttpError';
export const fetchJson = (url, options = {}) => {
const requestHeaders = options.headers || new Headers({
Accept: 'application/json',
'X-AA-ClientName': 'fc5f3712-64fc-4ca4-9e5f-d4b6edeb46d4',
'X-AA-ApiKey': '80b4ccbf-a741-42ad-aacc-50c4309de8e6',
});
if (!(options && options.body && options.body instanceof FormData)) {
requestHeaders.set('Content-Type', 'application/json');
}
if (options.user && options.user.authenticated && options.user.token) {
requestHeaders.set('Authorization', options.user.token);
}
return fetch(url, { ...options, headers: requestHeaders })
.then(response => response.text().then(text => ({
status: response.status,
statusText: response.statusText,
headers: response.headers,
body: text,
})))
.then(({ status, statusText, headers, body }) => {
let json;
try {
json = JSON.parse(body);
} catch (e) {
// not json, no big deal
}
if (status < 200 || status >= 300) {
return Promise.reject(new HttpError((json && json.message) || statusText, status));
}
return { status, headers, body, json };
});
};
export const queryParameters = data => Object.keys(data)
.map(key => [key, data[key]].map(encodeURIComponent).join('='))
.join('&');
The simple.js file is an exact copy from the repo.
What did I do wrong?
You need a dedicated auth client to handle the auth types and shoot the appropriate actions
https://marmelab.com/admin-on-rest/Admin.html#authclient
That's because your API response is not what the simpleRestClient expects:
It should only contains
[{"changeManagements":[],"serviceProfiles":[],"id":1,"login":"cuken","permissionLevel":9001,"note":"This is a dev test user"}]
No data nor totalItems keys. As stated in the documentation:
The simple REST client expects the API to include a Content-Range header in the response to GET_LIST calls. The value must be the total number of resources in the collection. This allows admin-on-rest to know how many pages of resources there are in total, and build the pagination controls.

CORS Issue When Requesting from ExtJS to node.js. Request or Response Header Incorrect?

I am having issues with making an ExtJS AJAX request to the Nodejs server between two different domains within our network and will appreciate any help. Response fails when attempting from both http and https from ExtJS client side but a Curl from my local via http returns 200 OK with proper data. We are working with content type application/json.
ExtJS onReady function has enabled CORS:
Ext.onReady(function () {
Ext.Ajax.cors = true;
Ext.Ajax.useDefaultXhrHeader = false;
... (code removed)
})
A test from my ExtJS client side on a known working URL that will properly create the ExtJS datastore (brings back 200 OK):
Ext.create('Ext.data.Store', {
id : 'countryStore',
model : 'country',
autoLoad : true,
autoDestroy: true,
proxy: {
type: 'rest',
url : 'https://restcountries.eu/rest/v1/all',
},
reader: {
type : 'json',
headers: {'Accept': 'application/json'},
totalProperty : 'total',
successProperty: 'success',
messageProperty: 'message'
}
});
However, when attempting a request to our Nodejs server via
http:
Ext.create('Ext.data.Store', {
id : 'circuits',
model : 'circuit',
autoLoad : true,
autoDestroy: true,
proxy: {
type: 'rest',
url : 'http://ourNodeJsServerDomain:5500/v3/circuits',
},
reader: {
type : 'json',
headers: {'Accept': 'application/json'},
totalProperty : 'total',
successProperty: 'success',
messageProperty: 'message'
}
});
returns the following in Chrome's console:
Mixed Content: The page at 'https://ourExtJsDevClientSide' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://ourNodeJsServerDomain:5500/v3/circuits?_dc=1430149427032&page=1&start=0&limit=50'. This request has been blocked; the content must be served over HTTPS.
Now, when attempted over https:
Firefox shows:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ourNodeJsServerDomain:5500/v3/circuits?_dc=1430151516741&page=1&start=0&limit=50. This can be fixed by moving the resource to the same domain or enabling CORS.
and the Request Header doesn't show "application/json", is this an issue?:
Accept
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Host
ourNodeJsServerDomain:5500
Origin
https://ourExtJsDevClientSide
Referer
https://ourExtJsDevClientSide
User-Agent
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:37.0) Gecko/20100101 Firefox/37.0
I then tried with Curl to see what the responses were to help debug
on http gives a 200 OK response but Access-Control-Allow-Origin is undefined even when we are defining it as "*":
curl http://ourNodeJsServerDomain:5500/v3circuits?_limit=1 -v
> GET /v3/circuits?_limit=1 HTTP/1.1
> User-Agent: curl/7.37.1
> Host: ourNodeJsServerDomain:5500
> Accept: */*
>
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Access-Control-Allow-Origin: undefined
< Access-Control-Allow-Methods: GET
< Access-Control-Allow-Headers: Content-Type
< Content-Type: application/json; charset=utf-8
< Content-Length: 1126
< ETag: W/"MlbRIlFPCV6w7+PmPoVYiA=="
< Date: Mon, 27 Apr 2015 16:24:18 GMT
< Connection: keep-alive
<
[
{ *good json data returned here* } ]
then when I attempt to Curl via https
curl https://ourNodeJsServerDomain:5500/v3/circuits?_limit=1 -v
* Server aborted the SSL handshake
* Closing connection 0
curl: (35) Server aborted the SSL handshake
We have enabled CORS on our Nodejs server:
router
.all('*', function(req, res, next){
res.setHeader('Content-Type', 'application/json');
// res.setHeader("Access-Control-Allow-Origin", req.headers.origin);
// console.log('\n\nreq.headers.origin ===================== ' + req.headers.origin);
//I have tried allowing all * via res.SetHeader and res.header and neither is defining the Access-Control-Allow-Origin properly when curling
//res.setHeader("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Methods', 'GET');
res.header('Access-Control-Allow-Headers', 'Content-Type');
I have attempted to be detailed in my thought process and I am willing to try new ways to determine how to understand and solve this.
* SOLUTION *
The issue is mixed content from the browser. Our client UI is on https (secure) whereas we were requesting http (unsecure) content from the nodejs server. We needed to allow for our nodejs server to run on https
We generated SSL certifications and implemented them onto our nodejs server.
Within the nodejs code, we enabled CORS with the CORS module and are running both http and https servers:
// enable CORS for all requests
var cors = require('cors');
app.use(cors());
// for certifications
var credentials = {
key: fs.readFileSync('our.key'),
cert: fs.readFileSync('our.crt')
};
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
httpServer.listen(port, function() {
console.log('HTTP server listening on port ' + port);
});
httpsServer.listen(httpsPort, function() {
console.log('HTTPS server listening on port ' + httpsPort);
});
There seems to be issues with both CORS and HTTPS in your server... You should try this middleware for the CORS part, and make it work when accessing the page in raw HTTP first. As far as I know, you'll have to use different ports for HTTP and HTTPS. And you will also probably need to enable CORS credentials. As I said, I think you'd better make it work in HTTP first ;)
Then, on the Ext part, as already mentioned in comments, you should probably disable default headers (or you'll have to make all of them accepted by your server; see the first comment to this answer). But you need to do that on the proxy, because apparently it replaces the global setting in Ext.Ajax.
So, something like this:
Ext.create('Ext.data.Store', {
id : 'countryStore',
model : 'country',
autoLoad : true,
autoDestroy: true,
proxy: {
type: 'rest',
url : 'https://restcountries.eu/rest/v1/all',
useDefaultXhrHeader: false, // <= HERE
reader: {
type : 'json',
headers: {'Accept': 'application/json'},
totalProperty : 'total',
successProperty: 'success',
messageProperty: 'message'
}
} // <= and notice this change
});
Probably unrelated, but note that your indendation was incorrect and hid the fact that the reader option was applied to the store itself instead of the proxy (so it was ignored).

Ajax file upload in node.js

Want to upload a file using ajax for this using this uploader
http://valums.com/ajax-upload/
and in node.js write this code which is working with normal file upload without ajax .
console.log("request " + sys.inspect(req.headers));
req.on('data', function(chunk) {
console.log("Received body data:");
// console.log(chunk.toString());
});
var form = new formidable.IncomingForm();
form.parse(req, function(err,fields, files) {
console.log('in if condition'+sys.inspect({fields: fields, files: files}));
fs.writeFile("upload/"+files.upload.name, files.upload,'utf8', function (err) {
if (err) throw err;
console.log('It\'s saved!');
client.putFile("upload/"+files.upload.name, files.upload.name, function(err, res){
if (err) throw err;
if (200 == res.statusCode) {
console.log('saved to s3');
httpres.writeHead(200, {'content-type': 'text/plain'});
httpres.write('received 1upload:\n\n');
httpres.end();
}
});
});
});
But this is giving error ?
request { host: 'myhost:8001',
'user-agent': 'Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-language': 'en-us,en;q=0.5',
'accept-encoding': 'gzip, deflate',
'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'keep-alive': '115',
connection: 'keep-alive',
origin: 'http://myhost',
'access-control-request-method': 'POST',
'access-control-request-headers': 'content-type' }
events.js:45
throw arguments[1]; // Unhandled 'error' event
^
Error: bad content-type header, no content-type
at IncomingForm._parseContentType (/usr/local/lib/node/.npm/formidable/1.0.0/package/lib/formidable/incoming_form.js:196:17)
at IncomingForm.writeHeaders (/usr/local/lib/node/.npm/formidable/1.0.0/package/lib/formidable/incoming_form.js:109:8)
at IncomingForm.parse (/usr/local/lib/node/.npm/formidable/1.0.0/package/lib/formidable/incoming_form.js:65:8)
at Server.<anonymous> (/home/myfolder/myfolder/newcontentserver.js:29:18)
at Server.emit (events.js:67:17)
at HTTPParser.onIncoming (http.js:1108:12)
at HTTPParser.onHeadersComplete (http.js:108:31)
at Socket.ondata (http.js:1007:22)
at Socket._onReadable (net.js:678:27)
at IOWatcher.onReadable [as callback] (net.js:177:10)
I think problem is the content-type is not set in the headers By ajax file upload .thats why this error is coming how can i set the header in this uploader , or how can i make a file in node.js server by incoming data.
As it is using the xhr so i think i can't use the formidable.incomingform() what should i use?
Looking at the latest fileuploader.js source code on github he does set the content type
xhr.setRequestHeader("Content-Type", "application/octet-stream");
I believe your problem is elsewhere.

Resources