Giter Club home page Giter Club logo

workos-node's Introduction

WorkOS Node.js Library

npm Build Status

The WorkOS library for Node.js provides convenient access to the WorkOS API from applications written in server-side JavaScript.

Documentation

See the API Reference for Node.js usage examples.

Installation

Install the package with:

yarn add @workos-inc/node

Configuration

To use the library you must provide an API key, located in the WorkOS dashboard, as an environment variable WORKOS_API_KEY:

WORKOS_API_KEY="sk_1234"

Or, you can set it on your own before your application starts:

import WorkOS from '@workos-inc/node';

const workos = new WorkOS('sk_1234');

SDK Versioning

For our SDKs WorkOS follows a Semantic Versioning (SemVer) process where all releases will have a version X.Y.Z (like 1.0.0) pattern wherein Z would be a bug fix (e.g., 1.0.1), Y would be a minor release (1.1.0) and X would be a major release (2.0.0). We permit any breaking changes to only be released in major versions and strongly recommend reading changelogs before making any major version upgrades.

Beta Releases

WorkOS has features in Beta that can be accessed via Beta releases. We would love for you to try these and share feedback with us before these features reach general availability (GA). To install a Beta version, please follow the installation steps above using the Beta release version.

Note: there can be breaking changes between Beta versions. Therefore, we recommend pinning the package version to a specific version. This way you can install the same version each time without breaking changes unless you are intentionally looking for the latest Beta version.

We highly recommend keeping an eye on when the Beta feature you are interested in goes from Beta to stable so that you can move to using the stable version.

More Information

workos-node's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

workos-node's Issues

Types for errors

It seems like when the internal works api (api.workos.com) throws an error you just return it.
For example the api authenticateWithCode can throw an error for email verification, but the types for the errors are not in this library.

Can you guys please add a custom error type and interfaces for your errors?

Here is how I need to handle it now:

workos.userManagement.authenticateWithCode({ clientId, code }).catch((error) => {
	// The error code should be as described here:
	// https://workos.com/docs/reference/user-management/authentication-errors
	if (error.code === "email_verification_required") {
		context.set.status = 401; // unauthorized
		return error;
	}

	// Additional if clauses for other errors.

	// Else let the error bubble up
	throw error;
});

Now I have two problems, a) my API is not typed unless I create types for all the errors manually, and b) I need to write code to handle all the workOS errors to separate them from server errors, as can be seen I the if clause.

If you were to use custom error classes then problem "a" would be solved, and if you add types then problem "b" would be solved. Or better yet you could create both and type the classes so that we get the best of bth worlds.

My code would then look like this:

workos.userManagement.authenticateWithCode({ clientId, code }).catch((error) => {
	if (error instanceof AuthenticationError) {
		// handle works errors
	}

	// Else let the error bubble up
	throw error;
});

And the error will be typed!

userManagment.listAuthFactors

Hey

I have recently migrated a small internal application to Work OS, I am trying to currently implement a MFA using totp, but unfortunately the documentation is severely lacking some crucial information.

So I am using NextJS (still on the pages router instead of the app), from my understanding the flow of MFA in workOS goes like this

  1. Enroll a user in MFA
  2. Display the QR Code and let users scan through an authenticator app.
  3. Challenge the factor
  4. Verify the factor

While all this makes sense and I managed to put together an implementation that works but the issue is

 const challenge = await workos.mfa.challengeFactor({
      authenticationFactorId: mfaId,
    })

So this doesn't make any sense at all? the authenticationFactorId will change everytime a new enrollment is done, how can I possibly keep track of it?

In the docs, I also came across the following

  const user = await workos.userManagement.listAuthFactors({
    userId,
  })

I have tried using this method several times but I end up with the following error

UnprocessableEntityException: The following requirement must be met:
        property userId should not exist

`sendMagicAuthCode` not working

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)

This is because response.json() is called on every post request and this particular endpoint doesn't return a response so an error is thrown.

Suggestion: allow skipping of verification in `webhooks.constructEvent`

My app architecture separates the request authentication from the handling of webhook events.

webhook event --> [request authentication layer] --> [controllers] --> [services]
                     ^                                         ^
                     |                                         |
                     where we call `webhooks.verifyHeader`     |
                                                               |
                                                               where we call `webhooks.constructEvent`

It would be neat if we could skip or separate the webhooks.verifyHeader call from webhooks.constructEvent. I'll be happy to make a PR for this.

Export ProfileAndToken interface

Description:
For the sso option as you have other exported members you need to add the export for type ProfileAndToken

export * from './authorization-url-options.interface';
export * from './connection-type.enum';
export * from './connection.interface';
export * from './get-profile-and-token-options.interface';
export * from './profile.interface';

Needs to add only this line:
export * from './profile-and-token.interface';

Thnx

Node versions before 10 do not support new WorkOS Root CA

Legacy Node versions, which many apps still run on, bundle a set of root CAs and do not support the new root from Let's Encrypt for WorkOS's https://api.workos.com, which makes the service incompatible with legacy software as of August 10, 2022.

The error message returned from Axios is certificate has expired.

The fix requires allowing the consumer to pass an https.Agent instance into the WorkOS constructor which includes the valid root CA.

At the current time, the WorkOS SSL certificate indicates the chain is ISRG Root X2 > E1 > *.workos.com. The root CA file can be obtained from from Let's Encrypt directly. This is the "Self-Signed" pem file (cross-signed does not work in our testing) and is named isrg-root-x2.pem.

A simple test to see if your Node version supports the new certificate:

const axios = require('axios');

axios.get('https://api.workos.com')
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error.message);
  });

If this logs out certificate has expired then your Node version does not support the new SSL certificate.

Error building due to unsupported Node.js API usage in Edge Runtime

When attempting to build WorkOS's official Next.js example, I encountered the following error during the build process:

> [email protected] build /Users/chongshengsun/Downloads/next-authkit-example
> next build

   ▲ Next.js 14.1.4
   - Environments: .env.local

   Creating an optimized production build ...
 ⚠ Compiled with warnings

./node_modules/.pnpm/@[email protected]/node_modules/@workos-inc/node/lib/workos.js
A Node.js API is used (process.emitWarning at line: 135) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime

Import trace for requested module:
./node_modules/.pnpm/@[email protected]/node_modules/@workos-inc/node/lib/workos.js
./node_modules/.pnpm/@[email protected]/node_modules/@workos-inc/node/lib/index.js
./node_modules/.pnpm/@[email protected][email protected][email protected][email protected]/node_modules/@workos-inc/nextjs/dist/cjs/workos.js
./node_modules/.pnpm/@[email protected][email protected][email protected][email protected]/node_modules/@workos-inc/nextjs/dist/cjs/authkit-callback-route.js
./node_modules/.pnpm/@[email protected][email protected][email protected][email protected]/node_modules/@workos-inc/nextjs/dist/cjs/index.js

./node_modules/.pnpm/@[email protected]/node_modules/@workos-inc/node/lib/workos.js
A Node.js API is used (process.emitWarning at line: 139) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime

Import trace for requested module:
./node_modules/.pnpm/@[email protected]/node_modules/@workos-inc/node/lib/workos.js
./node_modules/.pnpm/@[email protected]/node_modules/@workos-inc/node/lib/index.js
./node_modules/.pnpm/@[email protected][email protected][email protected][email protected]/node_modules/@workos-inc/nextjs/dist/cjs/workos.js
./node_modules/.pnpm/@[email protected][email protected][email protected][email protected]/node_modules/@workos-inc/nextjs/dist/cjs/authkit-callback-route.js
./node_modules/.pnpm/@[email protected][email protected][email protected][email protected]/node_modules/@workos-inc/nextjs/dist/cjs/index.js

This error indicates that @workos-inc/node library is using an unsupported Node.js API usage in Edge Runtime.

Could you please investigate this issue and provide guidance on how to resolve it? Is there a way to make the @workos-inc/node library compatible with Next.js's Edge Runtime?

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v4
  • actions/setup-node v4
.github/workflows/fix-latest.yml
  • actions/checkout v4
  • actions/setup-node v4
.github/workflows/release.yml
  • actions/checkout v4
  • actions/setup-node v4
npm
package.json
  • pluralize 8.0.0
  • @peculiar/webcrypto ^1.4.5
  • @types/jest 29.5.3
  • @types/node 14.18.54
  • @types/pluralize 0.0.30
  • jest 29.6.2
  • jest-fetch-mock ^3.0.3
  • prettier 2.8.8
  • supertest 6.3.3
  • ts-jest 29.1.2
  • tslint 6.1.3
  • typescript 5.1.6
  • node >=19
  • node 19.9.0
  • yarn 1.22.19
nvm
.nvmrc
  • node 14.21.3

  • Check this box to trigger a request for Renovate to run again on this repository

ReferenceError: crypto is not defined

Hi,

I use workos-node v6.0.2, and get ReferenceError: crypto is not defined when I use constructEvent or verifyHeader functions.

Sample code:

const workos = new WorkOS(process.env.WORKOS_API_KEY);
app.post("/api/auth/events", async (req, res) => {
  const payload = req.body;
  const sigHeader = req.headers["workos-signature"] as string;

  try {
    const webhook = await workos.webhooks.verifyHeader({
      payload,
      sigHeader,
      secret: process.env.WEBHOOK_SECRET,
    });
  } catch (error) {
    console.log(error);
  }

  return res.status(200);
});

Could you help me?

Switch from axios to fetch?

Hi,

Have you considered updating this package to use fetch instead of Axios?

We are using @workos-inc/node with Cloudflare Workers/Pages, which do not support all the Node APIs that Axios requires.

Older versions of @workos-inc/node were using using [email protected], and there was a fetch adapter that was compatible with that version of Axios (https://github.com/vespaiach/axios-fetch-adapter). Unfortunately, the most recent version of @workos-inc/node depends on [email protected], and there doesn't seem to be a good fetch adapter for it.

Node v18 supports the fetch API (and you may be able to inject node-fetch or similar in earlier versions).

Alternatively, you could add a new workos-fetch package. But that may be too much work since I don't think the SDKs are auto-generated.

Thanks.

Export Error classes

Context

As part of using this library I'd like to be able to access the various custom Error classes this library uses for a couple of reasons:

  • Custom error handling based on error class (it's probably possible to detect which type is thrown based on properties, but it makes my code much clearer to check the class itself)
  • In tests, creating fakes/stubs/mocks which throw errors of the same type that the library itself throws

It does look like quite a lot is already exported, so I'm a bit surprised to see the ./common/exceptions module omitted:

https://github.com/workos-inc/workos-node/blob/ab16edced2291a0691406ade5a259519d4567311/src/index.ts#L3-L9

Question

Was there a reason that the exceptions module was omitted? (If no, would it be possible to export those error classes for use externally?)

Proposal

Perhaps usage like so would make sense, instead of just adding them to the root level of the module:

import { Errors as WorkOSErrors } from '@workos-inc/node'

throw new WorkOSErrors.NotFoundException(...)

PingOne and PingFederate authentication URLs seem to be encoded incorrectly

It seems that the way authentication URLs are generated for PingOne and PingFederate connections is incorrect.

The URL is created with the format: https://sso.connect.pingidentity.com/sso/idp/SSO.saml2?idpid=<idp-id-here>?SAMLRequest=<large-encoded-string-here>

You can see that the query params are encoded incorrectly. The second param, SAMLRequest, should be preceded by an ampersand (&) rather than a question mark (?).

I've confirmed that manually altering the URL by replacing the second question mark with an ampersand fixes the issue. We of course cannot manually alter every URL, and this is blocking us from rolling out SSO with a client at the moment.

Missing from Connection Types

I noticed there are a bunch of connections (https://workos.com/docs/reference/sso/connection) missing from the ConnectionType. Is there a reason for this?

export enum ConnectionType {
  ADFSSAML = 'ADFSSAML',
  Auth0SAML = 'Auth0SAML',
  AzureSAML = 'AzureSAML',
  GenericOIDC = 'GenericOIDC',
  GenericSAML = 'GenericSAML',
  GoogleOAuth = 'GoogleOAuth',
  GoogleSAML = 'GoogleSAML',
  MagicLink = 'MagicLink',
  OktaSAML = 'OktaSAML',
  OneLoginSAML = 'OneLoginSAML',
  PingFederateSAML = 'PingFederateSAML',
  PingOneSAML = 'PingOneSAML',
  VMwareSAML = 'VMwareSAML',
}

Allow customization of Axios instance

Problem

I'm using this SDK in a project running on Cloudflare Workers which is not a native Node runtime. Axios expects either XMLHttpRequest or Node's http module to be available which causes an error since Cloudflare Workers only supports the standard Fetch API.

Proposal

Axios accepts custom adapters to provide the underlying http client implementation. The adapter is specified within Request Config. I would like to customize the Axios client instance by passing in additional options to the WorkOS constructor. This could be done by passing in a Axios instance or the Request Config used to create the Axios instance. This would also be useful to create mock implementation for testing.

For example,

new WorkOS(key, {
  axios: axios.create({ adapter: myFetchAdapter })
});

Interface for `CreatePasswordlessSession` has a type issue

export interface CreatePasswordlessSessionOptions {
  email: string;
  redirectURI?: string;
  state?: string;
  type: 'MagicLink';
}

type can't equal 'MagicLink' as CreatePasswordlessSessionOptions is an interface and can't have concrete values. It's causing type issues when trying to use it in Typescript. type should equal string

Incompatibility with Cloudflare Workers

Although buffer is globally defined in a node environment, in an edge environment like Cloudflare Workers, Buffer has to be imported as "node:buffer". Frameworks like SvelteKit handle the conversion of "buffer" to "node:buffer" internally Link. However, in constructEvent, because Buffer is assumed to be globally defined. Screenshot 2024-02-17 225517

When deployed to Cloudflare, my SvelteKit application's webhook errors out with "Buffer not defined"
Screenshot 2024-02-17 224746

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Cannot find preset's package (github>whitesource/merge-confidence:beta)

WorkOS is not a constructor

const WorkOS = require('@workos-inc/node');

const workos = new WorkOS("sk_test_a2");
TypeError: WorkOS is not a constructor

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.