Code Monkey home page Code Monkey logo

Comments (12)

enisdenjo avatar enisdenjo commented on May 17, 2024 1

Of course! You can close the socket quite literally whenever you want. The client will behave accordingly.

from graphql-ws.

enisdenjo avatar enisdenjo commented on May 17, 2024 1

🎉 This issue has been resolved in version 2.0.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

from graphql-ws.

Amareis avatar Amareis commented on May 17, 2024

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.

Amareis avatar Amareis commented on May 17, 2024

Ohh, I see, after #64 is merged, it can be really done in userland, great!

from graphql-ws.

enisdenjo avatar enisdenjo commented on May 17, 2024

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.

Amareis avatar Amareis commented on May 17, 2024

Where is updated protocol? I can't see it on master nor in #64

from graphql-ws.

enisdenjo avatar enisdenjo commented on May 17, 2024

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.

Amareis avatar Amareis commented on May 17, 2024

Oh, just there is still code-reason pairs, so it's similar like they really enforced by spec.

from graphql-ws.

enisdenjo avatar enisdenjo commented on May 17, 2024

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.

Amareis avatar Amareis commented on May 17, 2024

What if I close socket in onConnect handler? Will it work properly?

from graphql-ws.

enisdenjo avatar enisdenjo commented on May 17, 2024

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.

Amareis avatar Amareis commented on May 17, 2024

Thank you!

from graphql-ws.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.