Coder Social home page Coder Social logo

fusionauth / fusionauth-typescript-client Goto Github PK

View Code? Open in Web Editor NEW
57.0 14.0 27.0 1.12 MB

A TypeScript client for FusionAuth

Home Page: https://fusionauth.io

License: Apache License 2.0

TypeScript 99.34% JavaScript 0.66%
fusionauth typescript rest api-client fusionauth-client

fusionauth-typescript-client's Introduction

FusionAuth TypeScript Client

semver 2.0.0 compliant npm

If you're integrating FusionAuth with a Typescript application, this library will speed up your development time. It also works with node and browser applications as well.

For additional information and documentation on FusionAuth refer to https://fusionauth.io.

Credits

  • Thanks to @tjpeden for your excellent contributions!

Installation

To install fusionauth-typescript-client, use npm

npm install @fusionauth/typescript-client

Refer to the FusionAuth API documentation to for request and response formats.

Development

  • Set up a fusionauth instance. (Not sure exactly how to configure, TBD.)
  • sb test

Questions and support

If you have a question or support issue regarding this client library, we'd love to hear from you.

If you have a paid edition with support included, please open a ticket in your account portal. Learn more about paid editions here.

Otherwise, please post your question in the community forum.

Contributing

Bug reports and pull requests are welcome on GitHub.

License

This code is available as open source under the terms of the Apache v2.0 License.

Upgrade Policy

This library is built automatically to keep track of the FusionAuth API, and may also receive updates with bug fixes, security patches, tests, code samples, or documentation changes.

These releases may also update dependencies, language engines, and operating systems, as we'll follow the deprecation and sunsetting policies of the underlying technologies that it uses.

This means that after a dependency (e.g. language, framework, or operating system) is deprecated by its maintainer, this library will also be deprecated by us, and will eventually be updated to use a newer version.

fusionauth-typescript-client's People

Contributors

elliottcarlson avatar fdaugs avatar fusionandy avatar lyleschemmerling avatar matthew-altman avatar mooreds avatar robfusion avatar robotdan avatar tjpeden avatar trex avatar tyduptyler13 avatar vcampitelli avatar voidmain avatar

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

Watchers

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

fusionauth-typescript-client's Issues

breaking when optional parameters omitted

Hi,

Some parameters are optional, as per the API doc but lib breaks if not provided.
This is specific of the typeScript lib, doesn't happen on node-client. It comes from the formData builder.

How to reproduce:

call

exchangeRefreshTokenForAccessToken('refreshToken', 'clientId', 'clientSecret')

Expected Result:

Request should be sent.

It should work with only those parameters, particularly, scope is optional. see doc: https://fusionauth.io/docs/v1/tech/oauth/endpoints#request-parameters-7

Actual result:

Type error at ligne

body.append('scope', scope);

because scope isn't provided

TypeError: Cannot read property 'name' of undefined
at FormData._getContentDisposition (/PATH/node_modules/@fusionauth/typescript-client/node_modules/form-data/lib/form_data.js:226:40)
at FormData._multiPartHeader (/PATH/node_modules/@fusionauth/typescript-client/node_modules/form-data/lib/form_data.js:177:33)
at FormData.append (/PATH/node_modules/@fusionauth/typescript-client/node_modules/form-data/lib/form_data.js:70:21)
at FusionAuthClient.exchangeRefreshTokenForAccessToken (/PATH/node_modules/@fusionauth/typescript-client/build/src/FusionAuthClient.js:795:14)

Note:

Works on the node-client:
https://github.com/FusionAuth/fusionauth-node-client/blob/3a36b95c04eb8e103967ca49c6548e6c4fdc0ef8/lib/FusionAuthClient.js#L928

Cheers

Register returns with HTTP 400

FusionAuth version: 1.13.2

The following code does not work currently. FusionAuth throws a 400, without any description of why it fails.

const client = new FusionAuthClient(
    <api_key>,
    <base_url>,
)

const registerAccountResponse = await client.register(uuid, {
    registration: {
        applicationId: APPLICATION_ID,
    },
        user: {
            email,
            password,
        },
    }
)

Manually crafting the request via Insomnia works, like so:

POST https://<base_url>/api/user/registration

Body

{
	"registration": {
		"applicationId": "<application_id>"
	},

	"user": {
		"email": "[email protected]",
		"password": "********"
	}
}

Headers
Content-Type: application/json
Authorization: <api_key>

I'm assuming that the client is not correctly passing the Authorization header it was instantiated with.

EDIT: After a debugging session, I've confirmed that the Authorization header is indeed correctly being set for the API call to FusionAuth.

Tried setting up a request via Axios like so, and also receive a 400 bad response:

    const registerAccountResponse = await axios.post(
        `${baseURL}/api/user/registration`,
        {
            registration: {
                applicationId: APPLICATION_ID,
            },
            user: {
                email,
                password,
            },
        },
        {
            headers: {
                'Content-Type': 'application/json',
                Authorization: API_KEY,
            },
        },
    )

Missing JWTManager

Summary

Per feedback from the community, logging this for tracking purposes. This functionality is present in the Java client.

https://fusionauth.io/learn/expert-advice/tokens/revoking-jwts/?ht-comment-id=608754

and also referenced in Doc

We are also writing JWTManager implementations into each of our client libraries so you don’t have to write those yourself. At the time of this writing, the Java and Node clients both have a JWTManager you can use. The other languages might have a JWTManager implementation now but if they don’t, just submit a support ticket or a Github issue and we will write one for you.
also, is this still true.  I searched for JWT and manager and could not find this in the typescript or java client. If the JWTManager development is deprecated, I can remove this bit from the article.

Accessing FA from localhost

I've created a React app that uses the fusionauth-typescript-client to connect to a self hosted FA instance.

The requests are blocked by the CORS policy (when developing locally) and I tried a couple of different setups for the FA CORS policy, but nothing seems to work as expected.

We don't want to create a backend gateway just to bypass the CORS policy on localhost, because the production web-apps are whitelisted and don't have this issue. Is there some sort of configuration we can specify or a particular way to setup/initialize the fusionauth-typescript-client to bypass this?

Thanks a lot for the help!

The host passed to the FusionAuthClient ctor must not end with a "/"

I've been tracking down that little bug for a few hours now, and finally I've found the problem. I have this code:

import { FusionAuthClient } from '@fusionauth/typescript-client'

const client = new FusionAuthClient(process.env.AUTH_API_KEY, process.env.AUTH_URL)

export const login = (user, password) => {
  return client.login({
    loginId: user,
    password,
    applicationId: process.env.AUTH_APP_ID
  })
}

I was not able to login with that code, because my AUTH_URL ended with a trailing /. In the application's console, I indeed can see that the FusionAuthClient sends its requests to the /api/login endpoint with two slashes in the address, i.e. something like this:

http://auth.shopozor//api/login

I would've expected such things to be handled by the client. Is that done like that by design or is that something you would consider fixing?

Browser example doesn't run when cloned

The browser example doesn't run when you first clone it.

$ cd fusionauth-typescript-client/examples/browser-example
$ ls -lrt
total 16
-rw-rw-r-- 1 vagrant vagrant 406 May 20 14:38 README.md
-rw-rw-r-- 1 vagrant vagrant 212 May 20 14:38 index.html
lrwxrwxrwx 1 vagrant vagrant  50 May 20 14:38 fusionauth-typescript-client.min.js.map -> ../../dist/fusionauth-typescript-client.min.js.map
lrwxrwxrwx 1 vagrant vagrant  46 May 20 14:38 fusionauth-typescript-client.min.js -> ../../dist/fusionauth-typescript-client.min.js
lrwxrwxrwx 1 vagrant vagrant  42 May 20 14:38 fusionauth-typescript-client.js -> ../../dist/fusionauth-typescript-client.js
-rw-rw-r-- 1 vagrant vagrant 937 May 20 14:38 example.js

The fusionauth javascript files point to files that don't exist in the repo, you have to build them with sb build which most people won't have.

Ideally the files would be generated by the client library build and then checked in.

EventType includes unused types

FusionAuth API version 1.48.1, running from docker container in development mode.
Typescript client version 1.48.0.

In the EventType enum the following members are defined in the type but are not returned from the API when provided

    AuditLogCreate = "audit-log.create",
    EventLogCreate = "event-log.create",
    KickstartSuccess = "kickstart.success",

This may be ultimately a bug in the API, as I can see those event types are listed in the docs as being available since 1.30.0, and I would expect those events to be in the tenant response if they were defined when the tenant was last updated.

Additionally, with EventConfiguration defined as:

export interface EventConfiguration {
    events?: Record<EventType, EventConfigurationData>;
}

This means that you must define all of the members of the enum when building an object of type Tenant, and the response from the API does not satisfy the type as declared.

Additionally, when working with the API, it seems that I don't need to provide all of the events when making requests to the API. When I send a PUT to the tenant endpoint with an incomplete list of events, the request is accepted just fine and then resulting GETs for that tenant return only the events I provided in the PUT.

I think it might make sense to modify EventConfiguration to something like:

export interface EventConfiguration {
    events?: { [key in EventType]?: EventConfigurationData }
}

Which would allow you to define only the events you want to send through to the API. Would this be a sensible change? Is it possible I have something misconfigured on my end?

I have a workaround on my end with type assertions, but I would love it if I could remove that and only define the events that I want to enable.

Incorrect use of Map type

Problem

There are a number of types defined using Map<K, V>, but they are not actually instances of Map, which leads to type warnings such as:

Element implicitly has an 'any' type because type 'Map<string, Error[]>' has no index signature. Did you mean to call 'get' ?

Solution

As far as I can tell, these are all plain objects, so Map<K, V> should be replaced with Record<K, V>

'missing_grant_type' error when using exchangeOAuthCodeForAccessToken in TypeScript

When using the TypeScript library, I always get the 'missing_grant_type' error when I use exchangeOAuthCodeForAccessToken.

My setup:

FusionAuth 1.16 (Docker)
TypeScript FusionAuth Client: 1.16.1
NodeJS 12.16.3

The same function works flawlessly with the NodeJS FusionAuth client. I looked at the code for the TypeScript version, and the code says "body.append("grant_type", "authorization_code")", so I'm wondering why it fails to recognize it.

Please let me know if you need further information.

Obscure error messages

If the incorrect credentials are entered a 404 is returned, and the parsing of the response body fails. This results in an obscure error:

exception: FetchError: invalid json response body at https://auth.nickbolles.com/api/login reason: Unexpected end of JSON input
      at C:\Users\nickb\Resilio Sync\Projects\goalsapp\project\packages\server\node_modules\node-fetch\lib\index.js:272:32
      at processTicksAndRejections (internal/process/task_queues.js:93:5) {
    message: 'invalid json response body at https://auth.nickbolles.com/api/login reason: Unexpected end of JSON input',
    type: 'invalid-json'
  }

Seems like that should be handled by the client and throw a better error. Took me a bit to figure out that I just missed a character in my email address... 😑

typescript definition lists all arguments as required when many are optional

The documentation for many functions (such as exchangeRefreshTokenForAccessToken) clearly states that many arguments are optional properties, but the typescript definition file lists all arguments as required.

The typescript functions should match the documentation so that users do not have to pass in null or undefined as arguments to avoid compiler errors.

Here is an example:

/**
     * Exchange a Refresh Token for an Access Token.
     * If you will be using the Refresh Token Grant, you will make a request to the Token endpoint to exchange the user’s refresh token for an access token.
     *
     * @param {string} refresh_token The refresh token that you would like to use to exchange for an access token.
     * @param {string} client_id (Optional) The unique client identifier. The client Id is the Id of the FusionAuth Application in which you you are attempting to authenticate. This parameter is optional when the Authorization header is provided.
     * @param {string} client_secret (Optional) The client secret. This value may optionally be provided in the request body instead of the Authorization header.
     * @param {string} scope (Optional) This parameter is optional and if omitted, the same scope requested during the authorization request will be used. If provided the scopes must match those requested during the initial authorization request.
     * @param {string} user_code (Optional) The end-user verification code. This code is required if using this endpoint to approve the Device Authorization.
     * @returns {Promise<ClientResponse<AccessToken>>}
     */
    exchangeRefreshTokenForAccessToken(refresh_token: string, client_id: string, client_secret: string, scope: string, user_code: string): Promise<ClientResponse<AccessToken>>;

return 405 when run client.exchangeOAuthCodeForAccessTokenUsingPKCE

I did the following tutorials using fastify.
https://fusionauth.io/docs/v1/tech/5-minute-setup-guide/

The login itself is working fine, but when I run client.exchangeOAuthCodeForAccessTokenUsingPKCE I get a 405 error.

There is no problem if it is executed by express as in the sample, but it fails when using fastify. Is there a sample of fastify?

log

2021-03-18 4:26:15.120 AM WARN  org.primeframework.mvc.action.DefaultActionMappingWorkflow - The action class [io.fusionauth.app.action.oauth2.TokenAction] does not have a valid execute method for the HTTP method [GET]

please help

Expose typedoc docs

Hi

It would be wonderful if you could expose the TypeDoc automatically generated docs, I think this will be beneficial for loads of users.

https://typedoc.org/

Especially the methods in FusionAuthClient are ideal. I know loads of IDEs expose all the type hinting automatically, be we are in an older project without all the fancy typescript stuff which makes the documentation a must-have

Possible conversion error when setting roles during register.

Hello!
First of all, thanks for the great work! I am using fusionauth-typescript-client from NestJs. Works great!

I noticed that you specified attribute roles?: Set<string> for interface UserRegistration located at FusionAuthClient.d.ts. I wonder, why not use: roles?: Array<string> ?

When I try to register a given user to an application using, for example, the following code snippet:

let finalRoles = new Set<string>(registration.roles); //registration.roles is just an array of strings.

const request: RegistrationRequest = {
                generateAuthenticationToken: false,
                registration: {
                    applicationId: finalOrgId,
                    roles: finalRoles, //USED HERE TO SEND START ROLES
                    verified: true
                },
                sendSetPasswordEmail: false,
                skipRegistrationVerification: true,
            }

        return this.aarmApClient.register(aarmAPSpecificAccId, request)        
        .catch(err=>{
            throw this.genError(err, 'AARMAccount', aarmAPSpecificAccId);
        })

FusionAuth Server returns:

{"statusCode":400,"exception":{"fieldErrors":{"registration.roles":[{"code":"[invalidJSON]","message":"Invalid JSON in the request body. The property was [registration.roles]. The error was [Possible conversion error]. The detailed exception was [Cannot deserialize instance of `java.util.TreeSet<java.lang.Object>` out of START_OBJECT token\n at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 1, column: 117] (through reference chain: io.fusionauth.domain.api.user.RegistrationRequest[\"registration\"]->io.fusionauth.domain.UserRegistration[\"roles\"])]."}]}}}

To test an alternative, I tried to alter FusionAuthClient.d.ts interface UserRegistration to

roles?: Array<string>;

and the used registration.roles array directly:

registration: {
                    applicationId: finalOrgId,
                    roles: registration.roles, <-- Array of strings now!
                    verified: true
                } 

Then it just works! I wonder why not simply declare the roles type as an Array of Strings instead of a Set<string>?

Regards,
Luiz Eduardo Giampaoli

Client and API Documentation don't align - searchEntityTypes

When I went to set the correct permissions on my API key to call the searchEntityTypes function, I visited the FusionAuth Entity Type documentation and found that the API call was a GET for searching entity types. I then set my api key to allow GET on /api/entity/type/search. However, I still received a 401, and after reading the client code, it makes a POST request instead, which doesn't align with the documentation. I'd like to understand which is correct - a GET or POST - and note that the discrepancy between the client and the documentation should be updated.

Build error with generated typings file

Typescript Version: 3.8.3

I'm running into build issues when trying to build an app containing the depency @fusionauth/[email protected].

This is the build error:

node_modules/@fusionauth/typescript-client/build/src/FusionAuthClient.d.ts:4:6 - error TS1023: An index signature parameter type must be either 'string' or 'number'.

4     [key: K]: T;
       ~~~

I've tried to find the corresponding line in the sourcecode but i couldn't find an interface with the name ObjectMap.

actionUser `expiry` field cannot be set to "infinity" (9223372036854775807)

Reference: https://fusionauth.io/docs/v1/tech/apis/actioning-users/#take-an-action-on-a-user

To cause the action to be applied indefinitely, or until the action is canceled or modified, set this value to 9223372036854775807.

Since Java API uses Long and the expiry field TypeScript definition uses number, trying to use that number literal will give TypeScript warning "Numeric literals with absolute values equal to 2^53 or greater are too large to be represented accurately as integers.ts(80008)"

And also when executing the result is:

Invalid JSON in the request body. The property was [action.expiry]. The error was [Possible conversion error]. The detailed exception was [Numeric value (9223372036854776000) out of range of long (-9223372036854775808 - 9223372036854775807)
 at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 1, column: 181] (through reference chain: io.fusionauth.domain.api.user.ActionRequest["action"]->io.fusionauth.domain.api.user.ActionRequest$ActionData["expiry"])].

Workaround

Use: '9223372036854775807' as any

Proposed Solution

If possible, change the type to number | string | undefined which is probably a good-enough compromise retaining backwards compatibility.

If not possible, then string | undefined is more flexible.

SDK method to return current access token or refresh it if expired

Hi team.

I am trying to mimic SDK behavior available in Auth0 js client or AWS Cognito js client (Amplify), which both provide SDK method to retrieve current token or automatically refresh it silently and return refreshed one, so that one dont have to handle expiration manually.

Auth0 will always return current(refreshed if needed) token with
Auth0.getTokenSilently()

Cognito provides similar approach with
const session = await Auth.currentSession().getAccessToken();

Again, it will refresh token if expired under the hood

Is there smth similar in FusionAuth js client that will abstract getting fresh token flow into single function?

[Feature] Custom RESTClient support

Currently this library is only compatible with the browser due to explicit usage of XMLHttpRequest. This means nodejs has no way to make a request as this is missing from its scope/api.

One option is to use https://www.npmjs.com/package/xhr as an abstraction layer so that it is compatible with both nodejs and the browser.

calling wasSuccessful throws an exception

When I try to call wasSuccessful() an exception is thrown from

TypeError: Cannot read property 'statusCode' of undefined
   at wasSuccessful (.../node_modules/@fusionauth/typescript-client/src/ClientResponse.ts:23:17)
   at .../dist/apps/api/webpack:/apps/api/src/app/services/auth.ts:72:43

When I inspect the javascript of the library, I see that indeedstatusCode does not exist on the class ClientReponse.

The generated javascript does not appear to match the typescript definition.

image

'loginConfiguration' and 'lambdaConfiguration' not working when createApplication

Hi,
I'm trying to set some configurations (like 'loginConfiguration', 'lambdaConfiguration') when using createApplication, but none of them is working!
in the response it shows that these configs are properly set, but actually its not! Im checking it with another 'get' request, and those are not set!
this is my request body:
{ application: { name: "test", loginConfiguration: { allowTokenRefresh: true, generateRefreshTokens: true }, lambdaConfiguration: { accessTokenPopulateId: "some-id" } } }
after creating all those configs will be with default values. If I try createApplication with Postman directly (POST /api/application/), it is working fine!

patchRegistration not working as intended

patchRegistration(userId: UUID, request: RegistrationRequest): Promise<ClientResponse<RegistrationResponse>> {

I was attempting to use the patchRegistration call linked above and noticed it was wiping out / overwriting registration information instead of updating an entry / adding to an array. This endpoint looks like it is actually hitting the Create a User Registration for an existing User endpoint because the application ID is not being added to the URI. To test this I made a direct http patch call through axios and it works as expected (in alignment with the documentation for this endpoint)

Validation of signed JWTs in an offline manner

I'm currently calling validateJWT() on every request from my microservices to validate the JWT. While I'm sure this may be a very lightweight request, but can FusionAuth provide advice or examples for, say, validating the token on some microservice without having to make requests to the auth server?

The current implementation of validateJWT() appears to make a network requests per invocation like so:

  validateJWT(encodedJWT: string): Promise<ClientResponse<ValidateResponse>> {
    return this.startAnonymous<ValidateResponse, void>()
        .withUri('/api/jwt/validate')
        .withAuthorization('Bearer ' + encodedJWT)
        .withMethod("GET")
        .go();
  }

Provide method to generate the /oauth2/logout method

I searched through the code but I couldn't find a method that can be invoked to have the /oauth2/logout URL.

It would be great to have such a method in order to always use the client to send all of the requests.

ValidateResponse type is wrong

Hi,

ValidateResponse returned from validateJWT is wrongly typed. The definition says:

ValidateResponse.jwt?: Map<string, any>

but the response returns a plain object instead. This will make either the app crash (no methods of Map available) or the compiler complain.

I would suggest rather a different interface definition, e.g.

// see https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields
interface JWT {
  exp: number; // Date expressed as epoch milliseconds as returned by the API
  iat: number;  // Date expressed as epoch milliseconds as returned by the API
  sub: string;
  iss: string;
  aud: string;
  [x: string]: any; // any other option - see https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#strict-object-literal-assignment-checking
}

ValidateResponse.jwt?: JWT

Typescript type definitions incomplete for NodeJS

I'm using TypeScript both on the front- and back-end. This library doesn't make it immediately clear that it has front-end dependencies, at least in the types, as is immediately obvious if you install this with a TypeScript Node application.

Please update the Readme, and whatever else necessary to make that more clear.

Passing configuration object to FusionAuthClient 🤔

Would be a syntactic improvement (if you ask me) if you could pass a configuration object to FusionAuthClient instead of directly passing the constructor values.

For readability it looks a tad nicer if you got

const client= new FusionAuthClient(
  { 
    apiKey: "asda-sd-asd",
    host: "https://localhost",
    tennantId: "bla-bla-bla"
  }
)

ClientResponse `exception` key should be defined as `Errors` type instead of `Error`

Referring to this line, shouldn't the defined type be Errors to conform with the interface found here? Right now, Error refers to the standard JS error class instead.

Also, I am not sure if importing ClientResponse directly in my code is the right thing to do. Shouldn't there be a named export inside FusionAuthClient.ts that corresponds with the schema of ClientResponse?

The reason I need this is for defining error handling inside catch blocks for errors originating from the FusionAuth library.

The other alternative is to handle catch errors with the any type but I don't like that and I don't want that to be a standard thing in our app.

Sorry if I am completely wrong with my approach as I am just getting acquainted with TypeScript. In which case, would you let me know how I can define FusionAuth errors correctly in my catch blocks?

retrieveUserByX does not allow specification of a tenant id

The following methods do not allow the specification of a tenant id, which is problematic when you have multiple tenants:

  • retrieveUserByUsername
  • retrieveUserByEmail
X-FusionAuth-TenantId [String] OPTIONAL
The unique Id of the tenant used to scope this API request.

When only a single tenant is configured the tenant Id can be assumed and this additional header is optional. Once more than one tenant has been configured in FusionAuth the tenant Id is required for this request because the input parameters by themselves do not indicate which tenant the request is intended.

The tenant Id may be provided through this header or by using a tenant locked API key to achieve the same result.

ObjectMap interface definition error

Client version: 1.15.8

Problem
Current definition of the ObjectMap interface in FusionAuthClient.ts:

export interface ObjectMap<K extends string | number, T> {
  [key: K]: T
}

This leads to the compilation error:
TS1023: An index signature parameter type must be either 'string' or 'number'.

Possible solutions

  1. Preferably remove the ObjectMap interface from the codebase in favor of built-in utility type Record<K,T>

  2. Otherwise rewrite the ObjectMap as type alias to support union keys:

export type ObjectMap<K extends string | number, T> = {
  [key in K]: T
}

Issues with building app with fusionauth-typescript-client

When I try to build app tsc --build with lib installed, I get an error like this:

node_modules/@fusionauth/typescript-client/build/src/IRESTClient.d.ts:3:46 - error TS7016: Could not find a declaration file for module 'node-fetch'. '/Users/.../node_modules/@fusionauth/typescript-client/node_modules/node-fetch/lib/index.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/node-fetch` if it exists or add a new declaration (.d.ts) file containing `declare module 'node-fetch';`

import { RequestCredentials, Response } from "node-fetch";

node_modules/@fusionauth/typescript-client/build/src/FusionAuthClient.d.ts:3:36 - error TS7016: Could not find a declaration file for module 'node-fetch'. '/Users/.../node_modules/@fusionauth/typescript-client/node_modules/node-fetch/lib/index.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/node-fetch` if it exists or add a new declaration (.d.ts) file containing `declare module 'node-fetch';`

import { RequestCredentials } from "node-fetch";
             

Typescript and lib versions:

  • typescript 4.3.5
  • @fusionauth/typescript-client: 1.30.0

The quick fix is to add "@types/node-fetch": "^2.5.7" to dependencies.

Current version of node-fetch already contains types but, there is no such type like RequestCredentials.

Is there any other fix ? or is it possible to update node-fetch here to the latest one ?

ClientResponse seems to be exported incorrectly

It seems to be not possible to

import { ClientResponse } from '@fusionauth/typescript-client;

The only way seems to be

import ClientResponse from '@fusionauth/typescript-client/build/src/ClientResponse';

ReferenceError: FormData is not defined

I was migrating over from the @fusionauth/node-client and I ended up getting this error ReferenceError: FormData is not defined when calling the exchangeOAuthCodeForAccessToken method.

Am I missing a dependency? I tried to install the FormData npm packge, but that didn't work. I'm kind of new to node, so any help would be greatly appreciated!

NPM missing latest version 1.10.2

We get an error due to a conflict between xhr and another package in our project using version 1.10.0. @tjpeden has submitted the fix to this which has been accepted as version 1.10.2. Any idea when you plan to update NPM with the latest changes?

We are currently having to compile and link the changes @tjpeden made which is less than desirable as we incorporate fusionauth to the rest of our development team.

Recent change broke browser support.

@tyduptyler13 @robotdan the change introduced by this commit isn't working for me in the browser. There's never a response.body, even for a normal 200 response (with a body). I also don't see that property on the response object with console.dir. I checked in both FF DE 72 and Chromium 79. I assume this is working for @tyduptyler13 because it was tested in Node.JS and the node-fetch implementation already includes the body property, but browser support isn't there.

My understanding of the it was written before my chance and the way I wrote my change is that if there was no body, it would (as @tyduptyler13 said) throw an error, which would be caught and stored in clientResponse.exception which if clientResponse.wasSuccessful() returns true, could safely be ignored.

exchangeRefreshTokenForAccessToken breaks compatibility with node-client

So I don't know if the current behavior is good or not, but I know it differs from the node-client and breaks compatibility.

I use to call the following without error with the node-client

await fusionAuthClient.exchangeRefreshTokenForAccessToken(
  refreshToken, clientID, clientSecret
)

Now the same code gives me the following error:

ClientResponse {
  statusCode: 400,
  exception: {
    error: 'invalid_scope',
    error_description: 'The scope provided is different than the scope used to generate the refresh token.'
  }
}

To fix it, I need to modify my code and add the scope parameter:

await fusionAuthClient.exchangeRefreshTokenForAccessToken(
  refreshToken, clientID, clientSecret, 'offline_access'
)

I'm raising that as an issue because the readme in node-client implies that there will be compatibility:
https://github.com/FusionAuth/fusionauth-node-client#deprecation-warning

You can just change your dependency and should have no problems using it with node as the package is still javascript but with additional type information. If you run into problems then let us know over there.

Missing API: changePasswordByJWT that accepts a JWT token

Currently only changePasswordByIdentity is given, however there is API for change password using JWT, but it's currently not possible:

return this.start<void, Errors>()
.withUri('/api/user/change-password')
.withJSONBody(request)
.withMethod("POST")
.go();

Change password using JWT REST API: https://fusionauth.io/docs/v1/tech/apis/users/#change-a-users-password

Proxy/Agent parameters for Rest Client

Hello there,

I find myself in the unpleasant situation where I have a corporate proxy that is annoying me each time I try to make an HTTP Connection.

I see that FusionAuthClient has no way of adding a custom http agent, or at least proxy parameters (that should be passed via an agent).

I've also seen that the RESTClient class is based on node-fetch

The node-fetch options for setting an agent are explained here https://github.com/node-fetch/node-fetch#custom-agent

Would it be possible to add an agent options to the client constructor? E.g.

// The following is one of many agent libraries that handle proxies
import { HttpsProxyAgent } from 'https-proxy-agent';

const fusionauthClient = new FusionAuthClient(
      apiKey,
      fusionAuthURL,
      tenantId,{
      agent: new HttpsProxyAgent({
            port: myProxyPort,
            host: myProxyHost
            // ....
      }) 
});

In this example I used HttpsProxyAgent however there are other libraries such as SocksProxyAgent and there could be perhaps other reasons to add a custom agent that are different from using a proxy.

client.logout("refreshtokien here") dont work

i was forced to replace method above with client.logoutWithRequest(logoutRequest); witch is basicly the same so it dont change anything but its still a bug

problem:
when calling client.logout(true, "refreshtokien here") i get exception that api consumes only application/json but api sends plain/text
method:

image

exception:

{
  "statusCode": 400,
  "exception": {
    "fieldErrors": {},
    "generalErrors": [
      {
        "code": "[InvalidContentType]",
        "message": "Invalid [Content-Type] HTTP request header value of [text/plain]. Supported values for this request include [application/json]."
      }
    ]
  }
}

UpdateUser Changes the Password Unexpectedly

In my API, I am using the Typescript client, v1.30.2. My API in general interacts with our FusionAuth account by making calls Bia the TS client.
I have a service function for updating a user. It takes in a user DTO model with properties that I need to change (ex. firstName, last name, etc). The DTO implements the FA User model.

In my service, the code flow is: I look up the user in FusionAuth by searchUsersByQuery() and the user's email. That returns the user model. I then update the fields of that model with the values passed in the arguments like this:
const updatedUserModel = { ...userSearch.response.users[0], ...userRequest, };

That produces a full FA user model, with only the properties updated that were passed in. I then create a UserRequest:
const updateRequest: UserRequest = { applicationId: XXXXXXXXXXX, sendSetPasswordEmail: false, skipVerification: true, user: updatedUserModel, };

And pass that into updateUser() method.

In general this all goes fine, and I see the data updates. However, this seems to be changing the password value as well. For the user I updated, if I then log them out via the API and then back in, the login() returns a Not Found response for my user.

If I go into the FA admin UI and edit the user, asetting their password back to what it should be, the login works again.

Is this a bug or expected behavior? I ideally don't want to pass the user's password every time I update their data. My site code that calls all this will only pass specific values being updated from the are of the site, so I'm passing small update packets over.

Unable to use exchangeOAuthCodeForAccessToken

I get a 500 error when I am trying to use the code on this branch: https://github.com/FusionAuth/fusionauth-example-node/tree/update-to-typescript

This app worked fine with the node client (I can dig up the commit if that will help, it's on that branch).

I have a 1.16.0 new fusionauth instance pulled from docker this morning.

I can make an API call just fine (in the test route), but exchangeOAuthCodeForAccessToken doesn't work.

When I start the express server by running npm start after installing the modules, I get the login page just fine and am sent to the FusionAuth login screen. When I enter the password, the browser just spins. The console of the node server shows:

{"statusCode":500,"exception":{"generalErrors":[{"code":"[Exception]","message":"FusionAuth encountered an unexpected error. Please contact support for assistance."}]}}

But there are no errors in any of the fusionauth logs in the admin ui.

I hacked the node_modules/@fusionauth/typescript-client/build/src/FusionAuthClient.js file to show what was being built with form-data (added this: console.log(body.getBuffer().toString()); to the exchangeOAuthCodeForAccessToken method) and saw this:

----------------------------255932213824836718829092
Content-Disposition: form-data; name="code"

jt32l0sVowmK_R8kJgccR-QDhhsFFWOewjYTFRDkq30
----------------------------255932213824836718829092
Content-Disposition: form-data; name="client_id"

d827b811-3d03-4cc0-96c3-914077219e7d
----------------------------255932213824836718829092
Content-Disposition: form-data; name="client_secret"

U4FUYnEgAKQcSpik7SuZh17ZzMan9zzbALGjeUHd89M
----------------------------255932213824836718829092
Content-Disposition: form-data; name="grant_type"

authorization_code
----------------------------255932213824836718829092
Content-Disposition: form-data; name="redirect_uri"

http://localhost:3000/oauth-redirect
----------------------------255932213824836718829092--

These values match what are in the FA admin screen.

Note that when I was going against a 1.15.5 FA server, I saw this error message:

ClientResponse {
  statusCode: 400,
  exception: {
    error: 'invalid_request',
    error_description: 'The request is missing a required parameter: grant_type',
    error_reason: 'missing_grant_type'
  }
}

Failing to publish 1.7.1 to NPM

Running : > npm publish --access=public


> @fusionauth/[email protected] prepare .
> npx browserify index.ts --debug -p tsify -o dist/fusionauth-typescript-client.js

TypeScript error: build/src/FusionAuthClient.ts(54,55): Error TS2314: Generic type 'ClientResponse<T>' requires 1 type argument(s).
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @fusionauth/[email protected] prepare: `npx browserify index.ts --debug -p tsify -o dist/fusionauth-typescript-client.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the @fusionauth/[email protected] prepare script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/degroff/.npm/_logs/2019-06-13T23_19_14_002Z-debug.log
~/dev/inversoft/fusionauth/fusionauth-typescript-client on  master

Can you take a look? Maybe an issue with the domain stuff?

User Search by Ids Fails with multiple Ids

Problem

client.userSearchByIds and client.userSearchByQuery using ids are incoherent and give different results.

How to recreate

When I am searching for users by id, I have two options. Either the client.userSearchByIds or client.userSearchByQuery using ids. Therefore I would prefer the first one, but when I give it a list of ids, an error gets returned. When I use the same setup but with client.userSearchByQuery using ids, I get a good result.

console.log(await client.searchUsersByQuery(
{
  search:
  {
    ids: users.map((user) => user.id),
  },
}));
>> HTTP CODE: 200


console.log(await client.searchUsersByIds(users.map((user) => user.id)));
>> HTTP CODE: 400
{"statusCode":400,"exception":{"fieldErrors":{"ids":[{"code":"[couldNotConvert]ids","message":"Invalid"}]},"generalErrors":[{"code":"[invalid]","message":"You must specify either the [ids], [queryString], or [query] property."}]}}

This only happens for more than 1 id, otherwise I get the same results.

Setting
I am still running on the v1.22.2, should this bug already be solved, please close this issue, but I could not find it in the Release Notes and this Issues here on github.

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.