Comments (12)
Of course! You can close the socket quite literally whenever you want. The client will behave accordingly.
from graphql-ws.
🎉 This issue has been resolved in version 2.0.0 🎉
The release is available on:
Your semantic-release bot 📦🚀
from graphql-ws.
Or, maybe it's better to throw special error? And then error.message will be close reason and (optional) error.code will be close code. I think it's even better than handle return value.
from graphql-ws.
Ohh, I see, after #64 is merged, it can be really done in userland, great!
from graphql-ws.
Hey hey, great insight!
I recently updated the Protocol to be more allowing in the aspect of authentication. Close socket with code and reason, authenticate before WS upgrade, authenticate on subscribe - the Protocol does not care.
Exactly, you found the correct PR! With #64 you literally implement your own server. The lib will only give you the minimal controls to transport GraphQL as per the spec; so yeah, once #64 lands - you have the total power of controlling the authentication flow.
from graphql-ws.
Where is updated protocol? I can't see it on master nor in #64
from graphql-ws.
The updated Protocol is the one on master! Adjustment was made 18 days ago, here: fb2ab09.
Was just pointing out that you can still be spec compliant and authenticate however you want.
from graphql-ws.
Oh, just there is still code-reason pairs, so it's similar like they really enforced by spec.
from graphql-ws.
Yes, and those will stay. They are tightly related to the spec itself and I'd like them to be enforced.
However, you may close the socket however you want for any other logic outside of the spec (like auth).
from graphql-ws.
What if I close socket in onConnect handler? Will it work properly?
from graphql-ws.
Hey @Amareis, as you may noticed, #64 has been released! This is how you'd go by implementing your own auth error handling:
// check extended implementation at `{ useServer } from 'graphql-ws/lib/use/ws'`
import http from 'http';
import ws from 'ws'; // yarn add ws
import { makeServer } from '../index';
import { execute, subscribe } from 'graphql';
import { schema } from 'my-graphql-schema';
import { validate } from 'my-auth';
// extra in the context
interface Extra {
readonly request: http.IncomingMessage;
}
// your custom auth
class Forbidden extends Error {}
function handleAuth(request: http.IncomingMessage) {
// do your auth on every subscription connect
const good = validate(request.headers['authorization']);
// or const { iDontApprove } = session(request.cookies);
if (!good) {
// throw a custom error to be handled
throw new Forbidden(':(');
}
}
// make
const server = makeServer<Extra>({
schema,
execute,
subscribe,
onConnect: async (ctx) => {
// do your auth on every connect
await handleAuth(ctx.extra.request);
},
onSubscribe: async (ctx) => {
// or maybe on every subscribe
await handleAuth(ctx.extra.request);
},
onNext: async (ctx) => {
// haha why not on every result emission?
await handleAuth(ctx.extra.request);
},
});
// create websocket server
const wsServer = new ws.Server({
server,
path: '/graphql',
});
// implement
wsServer.on('connection', (socket, request) => {
// pass the connection to graphql-ws
const closed = server.opened(
{
protocol: socket.protocol, // will be validated
send: (data) =>
new Promise((resolve, reject) => {
// control your data flow by timing the promise resolve
socket.send(data, (err) => (err ? reject(err) : resolve()));
}),
close: (code, reason) => socket.close(code, reason), // for standard closures
onMessage: (cb) => {
socket.on('message', async (event) => {
try {
// wait for the the operation to complete
// - if init message, waits for connect
// - if query/mutation, waits for result
// - if subscription, waits for complete
await cb(event.toString());
} catch (err) {
// all errors that could be thrown during the
// execution of operations, will be caught here
if (err instanceof Forbidden) {
// your magic
} else {
socket.close(1011, err.message);
}
}
});
},
},
// pass request to the extra
{ request },
);
// notify server that the socket closed
socket.once('close', () => closed());
});
from graphql-ws.
Thank you!
from graphql-ws.
Related Issues (20)
- Warning when importing module with rollup
- limitCloseReason crash with Cannot read properties of undefined HOT 2
- On Normal Closure the app doesn't retry even when shouldRetry set to true
- Websocket event "connection_ack" with "payload" as null result into closed connection HOT 3
- Invalid message Error in subscription
- Support for "graphql-ws" sub protocol
- graphql-transport-ws rejection specification HOT 7
- Cannot return null for non-nullable field Subscription.greeting
- "realTimeConsumptionEnabled": false HOT 1
- Docs folder is missing HOT 1
- Npm and tsc build fails on 5.13.0 due to bun-types HOT 2
- graphql-yoga integration example breaks for mutations HOT 2
- JWT Expired gives fatal error. How to refresh the JWT token for an open GraphQL subscription? HOT 4
- Refresh JWT Token in connection init
- Malformed authorization headers on [email protected] only on iOS HOT 4
- Socket could not reconnect after IOS app comeback from background
- wrong protocol in connection
- Detecting when a websocket connection is down
- [ReactNative] Slow refresh subscription causes websocket close with {"isTrusted": false, "message": null} HOT 18
- Retry on different URL HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from graphql-ws.