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)
- Allow to update connectionParams
- fix incorrect Bad Gateway error code HOT 3
- Subscriptions not working with Hasura via apollo Client graphql. error - Error: WebSocket implementation missing; HOT 1
- rename onMessage in server to postMessage, withMessage (or something more appropriate) HOT 1
- How to use `graphql-ws` protocol?
- Websocket using bun server - Unable to access request object in ctx.extras
- Warning Workspaces can only be enabled in private projects. HOT 3
- Detect subscription successfully started
- Errors during streaming subscriptions aren't properly handled or emitted HOT 1
- httpOnly cookie authentication
- Promises getting rejected with non-Error objects HOT 2
- Some subscriptions remain open after a websocket has been closed HOT 2
- Getting "Internal error occurred during message handling. Please check your implementation." after following recipe
- Clarify Contribution Policy
- Clients can be sent an `Error` message after cancellation. HOT 2
- How to avoid logging of hole object in graphql-ws?
- Consider migrating to crossws
- Make code and reason optional when closing a connection HOT 2
- fastify websockets breaking change HOT 4
- ERROR CREATING WsLink
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.