mirror of
https://github.com/Abdulazizzn/n8n-enterprise-unlocked.git
synced 2025-12-17 01:56:46 +00:00
fix: Revert "Replace client-oauth2 with an in-repo package" (no-changelog) (#6265)
Revert "feat(core): Replace client-oauth2 with an in-repo package (#6056)"
This reverts commit 77ac953eaf.
This commit is contained in:
committed by
GitHub
parent
8ae2d801d8
commit
b7d30f3eab
@@ -1,14 +0,0 @@
|
||||
const { sharedOptions } = require('@n8n_io/eslint-config/shared');
|
||||
|
||||
/**
|
||||
* @type {import('@types/eslint').ESLint.ConfigData}
|
||||
*/
|
||||
module.exports = {
|
||||
extends: ['@n8n_io/eslint-config/base'],
|
||||
|
||||
...sharedOptions(__dirname),
|
||||
|
||||
rules: {
|
||||
'@typescript-eslint/consistent-type-imports': 'error',
|
||||
},
|
||||
};
|
||||
@@ -1,2 +0,0 @@
|
||||
/** @type {import('jest').Config} */
|
||||
module.exports = require('../../../jest.config');
|
||||
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"name": "@n8n/client-oauth2",
|
||||
"version": "0.1.0",
|
||||
"scripts": {
|
||||
"clean": "rimraf dist .turbo",
|
||||
"dev": "pnpm watch",
|
||||
"typecheck": "tsc",
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"format": "prettier --write . --ignore-path ../../../.prettierignore",
|
||||
"lint": "eslint --quiet .",
|
||||
"lintfix": "eslint . --fix",
|
||||
"watch": "tsc -p tsconfig.build.json --watch",
|
||||
"test": "jest",
|
||||
"test:dev": "jest --watch"
|
||||
},
|
||||
"main": "dist/index.js",
|
||||
"module": "src/index.ts",
|
||||
"types": "dist/index.d.ts",
|
||||
"files": [
|
||||
"dist/**/*"
|
||||
],
|
||||
"dependencies": {
|
||||
"axios": "^0.21.1"
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-return */
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-argument */
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
|
||||
/* eslint-disable @typescript-eslint/restrict-plus-operands */
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import * as qs from 'querystring';
|
||||
import axios from 'axios';
|
||||
import { getAuthError } from './utils';
|
||||
import type { ClientOAuth2TokenData } from './ClientOAuth2Token';
|
||||
import { ClientOAuth2Token } from './ClientOAuth2Token';
|
||||
import { CodeFlow } from './CodeFlow';
|
||||
import { CredentialsFlow } from './CredentialsFlow';
|
||||
import type { Headers, Query } from './types';
|
||||
|
||||
export interface ClientOAuth2RequestObject {
|
||||
url: string;
|
||||
method: 'DELETE' | 'GET' | 'HEAD' | 'PATCH' | 'POST' | 'PUT';
|
||||
body?: Record<string, any>;
|
||||
query?: Query;
|
||||
headers?: Headers;
|
||||
}
|
||||
|
||||
export interface ClientOAuth2Options {
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
accessTokenUri: string;
|
||||
authorizationUri?: string;
|
||||
redirectUri?: string;
|
||||
scopes?: string[];
|
||||
authorizationGrants?: string[];
|
||||
state?: string;
|
||||
body?: Record<string, any>;
|
||||
query?: Query;
|
||||
headers?: Headers;
|
||||
}
|
||||
|
||||
class ResponseError extends Error {
|
||||
constructor(readonly status: number, readonly body: object, readonly code = 'ESTATUS') {
|
||||
super(`HTTP status ${status}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct an object that can handle the multiple OAuth 2.0 flows.
|
||||
*/
|
||||
export class ClientOAuth2 {
|
||||
code: CodeFlow;
|
||||
|
||||
credentials: CredentialsFlow;
|
||||
|
||||
constructor(readonly options: ClientOAuth2Options) {
|
||||
this.code = new CodeFlow(this);
|
||||
this.credentials = new CredentialsFlow(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new token from existing data.
|
||||
*/
|
||||
createToken(data: ClientOAuth2TokenData, type?: string): ClientOAuth2Token {
|
||||
return new ClientOAuth2Token(this, {
|
||||
...data,
|
||||
...(typeof type === 'string' ? { token_type: type } : type),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to parse response body as JSON, fall back to parsing as a query string.
|
||||
*/
|
||||
private parseResponseBody<T extends object>(body: string): T {
|
||||
try {
|
||||
return JSON.parse(body);
|
||||
} catch (e) {
|
||||
return qs.parse(body) as T;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Using the built-in request method, we'll automatically attempt to parse
|
||||
* the response.
|
||||
*/
|
||||
async request<T extends object>(options: ClientOAuth2RequestObject): Promise<T> {
|
||||
let url = options.url;
|
||||
const query = qs.stringify(options.query);
|
||||
|
||||
if (query) {
|
||||
url += (url.indexOf('?') === -1 ? '?' : '&') + query;
|
||||
}
|
||||
|
||||
const response = await axios.request({
|
||||
url,
|
||||
method: options.method,
|
||||
data: qs.stringify(options.body),
|
||||
headers: options.headers,
|
||||
transformResponse: (res) => res,
|
||||
});
|
||||
|
||||
const body = this.parseResponseBody<T>(response.data);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const authErr = getAuthError(body);
|
||||
if (authErr) throw authErr;
|
||||
|
||||
if (response.status < 200 || response.status >= 399)
|
||||
throw new ResponseError(response.status, response.data);
|
||||
|
||||
return body;
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-argument */
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
import type { ClientOAuth2, ClientOAuth2Options, ClientOAuth2RequestObject } from './ClientOAuth2';
|
||||
import { auth, getRequestOptions } from './utils';
|
||||
import { DEFAULT_HEADERS } from './constants';
|
||||
|
||||
export interface ClientOAuth2TokenData extends Record<string, string | undefined> {
|
||||
token_type?: string | undefined;
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
expires_in?: string;
|
||||
scope?: string | undefined;
|
||||
}
|
||||
/**
|
||||
* General purpose client token generator.
|
||||
*/
|
||||
export class ClientOAuth2Token {
|
||||
readonly tokenType?: string;
|
||||
|
||||
readonly accessToken: string;
|
||||
|
||||
readonly refreshToken: string;
|
||||
|
||||
private expires: Date;
|
||||
|
||||
constructor(readonly client: ClientOAuth2, readonly data: ClientOAuth2TokenData) {
|
||||
this.tokenType = data.token_type?.toLowerCase() ?? 'bearer';
|
||||
this.accessToken = data.access_token;
|
||||
this.refreshToken = data.refresh_token;
|
||||
|
||||
this.expires = new Date();
|
||||
this.expires.setSeconds(this.expires.getSeconds() + Number(data.expires_in));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign a standardized request object with user authentication information.
|
||||
*/
|
||||
sign(requestObject: ClientOAuth2RequestObject): ClientOAuth2RequestObject {
|
||||
if (!this.accessToken) {
|
||||
throw new Error('Unable to sign without access token');
|
||||
}
|
||||
|
||||
requestObject.headers = requestObject.headers ?? {};
|
||||
|
||||
if (this.tokenType === 'bearer') {
|
||||
requestObject.headers.Authorization = 'Bearer ' + this.accessToken;
|
||||
} else {
|
||||
const parts = requestObject.url.split('#');
|
||||
const token = 'access_token=' + this.accessToken;
|
||||
const url = parts[0].replace(/[?&]access_token=[^&#]/, '');
|
||||
const fragment = parts[1] ? '#' + parts[1] : '';
|
||||
|
||||
// Prepend the correct query string parameter to the url.
|
||||
requestObject.url = url + (url.indexOf('?') > -1 ? '&' : '?') + token + fragment;
|
||||
|
||||
// Attempt to avoid storing the url in proxies, since the access token
|
||||
// is exposed in the query parameters.
|
||||
requestObject.headers.Pragma = 'no-store';
|
||||
requestObject.headers['Cache-Control'] = 'no-store';
|
||||
}
|
||||
|
||||
return requestObject;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh a user access token with the supplied token.
|
||||
*/
|
||||
async refresh(opts?: ClientOAuth2Options): Promise<ClientOAuth2Token> {
|
||||
const options = { ...this.client.options, ...opts };
|
||||
|
||||
if (!this.refreshToken) throw new Error('No refresh token');
|
||||
|
||||
const requestOptions = getRequestOptions(
|
||||
{
|
||||
url: options.accessTokenUri,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...DEFAULT_HEADERS,
|
||||
Authorization: auth(options.clientId, options.clientSecret),
|
||||
},
|
||||
body: {
|
||||
refresh_token: this.refreshToken,
|
||||
grant_type: 'refresh_token',
|
||||
},
|
||||
},
|
||||
options,
|
||||
);
|
||||
|
||||
const responseData = await this.client.request<ClientOAuth2TokenData>(requestOptions);
|
||||
return this.client.createToken({ ...this.data, ...responseData });
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the token has expired.
|
||||
*/
|
||||
expired(): boolean {
|
||||
return Date.now() > this.expires.getTime();
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
import * as qs from 'querystring';
|
||||
import type { ClientOAuth2, ClientOAuth2Options } from './ClientOAuth2';
|
||||
import type { ClientOAuth2Token, ClientOAuth2TokenData } from './ClientOAuth2Token';
|
||||
import { DEFAULT_HEADERS, DEFAULT_URL_BASE } from './constants';
|
||||
import { auth, expects, getAuthError, getRequestOptions, sanitizeScope } from './utils';
|
||||
|
||||
interface CodeFlowBody {
|
||||
code: string | string[];
|
||||
grant_type: 'authorization_code';
|
||||
redirect_uri?: string;
|
||||
client_id?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Support authorization code OAuth 2.0 grant.
|
||||
*
|
||||
* Reference: http://tools.ietf.org/html/rfc6749#section-4.1
|
||||
*/
|
||||
export class CodeFlow {
|
||||
constructor(private client: ClientOAuth2) {}
|
||||
|
||||
/**
|
||||
* Generate the uri for doing the first redirect.
|
||||
*/
|
||||
getUri(opts?: ClientOAuth2Options): string {
|
||||
const options = { ...this.client.options, ...opts };
|
||||
|
||||
// Check the required parameters are set.
|
||||
expects(options, 'clientId', 'authorizationUri');
|
||||
|
||||
const query: Record<string, string | undefined> = {
|
||||
client_id: options.clientId,
|
||||
redirect_uri: options.redirectUri,
|
||||
response_type: 'code',
|
||||
state: options.state,
|
||||
};
|
||||
if (options.scopes !== undefined) {
|
||||
query.scope = sanitizeScope(options.scopes);
|
||||
}
|
||||
|
||||
if (options.authorizationUri) {
|
||||
const sep = options.authorizationUri.includes('?') ? '&' : '?';
|
||||
return options.authorizationUri + sep + qs.stringify({ ...query, ...options.query });
|
||||
}
|
||||
throw new TypeError('Missing authorization uri, unable to get redirect uri');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the code token from the redirected uri and make another request for
|
||||
* the user access token.
|
||||
*/
|
||||
async getToken(
|
||||
uri: string | URL,
|
||||
opts?: Partial<ClientOAuth2Options>,
|
||||
): Promise<ClientOAuth2Token> {
|
||||
const options = { ...this.client.options, ...opts };
|
||||
|
||||
expects(options, 'clientId', 'accessTokenUri');
|
||||
|
||||
const url = uri instanceof URL ? uri : new URL(uri, DEFAULT_URL_BASE);
|
||||
if (
|
||||
typeof options.redirectUri === 'string' &&
|
||||
typeof url.pathname === 'string' &&
|
||||
url.pathname !== new URL(options.redirectUri, DEFAULT_URL_BASE).pathname
|
||||
) {
|
||||
throw new TypeError('Redirected path should match configured path, but got: ' + url.pathname);
|
||||
}
|
||||
|
||||
if (!url.search?.substring(1)) {
|
||||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
||||
throw new TypeError(`Unable to process uri: ${uri.toString()}`);
|
||||
}
|
||||
|
||||
const data =
|
||||
typeof url.search === 'string' ? qs.parse(url.search.substring(1)) : url.search || {};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const error = getAuthError(data);
|
||||
if (error) throw error;
|
||||
|
||||
if (options.state && data.state !== options.state) {
|
||||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
||||
throw new TypeError(`Invalid state: ${data.state}`);
|
||||
}
|
||||
|
||||
// Check whether the response code is set.
|
||||
if (!data.code) {
|
||||
throw new TypeError('Missing code, unable to request token');
|
||||
}
|
||||
|
||||
const headers = { ...DEFAULT_HEADERS };
|
||||
const body: CodeFlowBody = {
|
||||
code: data.code,
|
||||
grant_type: 'authorization_code',
|
||||
redirect_uri: options.redirectUri,
|
||||
};
|
||||
|
||||
// `client_id`: REQUIRED, if the client is not authenticating with the
|
||||
// authorization server as described in Section 3.2.1.
|
||||
// Reference: https://tools.ietf.org/html/rfc6749#section-3.2.1
|
||||
if (options.clientSecret) {
|
||||
headers.Authorization = auth(options.clientId, options.clientSecret);
|
||||
} else {
|
||||
body.client_id = options.clientId;
|
||||
}
|
||||
|
||||
const requestOptions = getRequestOptions(
|
||||
{
|
||||
url: options.accessTokenUri,
|
||||
method: 'POST',
|
||||
headers,
|
||||
body,
|
||||
},
|
||||
options,
|
||||
);
|
||||
|
||||
const responseData = await this.client.request<ClientOAuth2TokenData>(requestOptions);
|
||||
return this.client.createToken(responseData);
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import type { ClientOAuth2, ClientOAuth2Options } from './ClientOAuth2';
|
||||
import type { ClientOAuth2Token, ClientOAuth2TokenData } from './ClientOAuth2Token';
|
||||
import { DEFAULT_HEADERS } from './constants';
|
||||
import { auth, expects, getRequestOptions, sanitizeScope } from './utils';
|
||||
|
||||
interface CredentialsFlowBody {
|
||||
grant_type: 'client_credentials';
|
||||
scope?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Support client credentials OAuth 2.0 grant.
|
||||
*
|
||||
* Reference: http://tools.ietf.org/html/rfc6749#section-4.4
|
||||
*/
|
||||
export class CredentialsFlow {
|
||||
constructor(private client: ClientOAuth2) {}
|
||||
|
||||
/**
|
||||
* Request an access token using the client credentials.
|
||||
*/
|
||||
async getToken(opts?: Partial<ClientOAuth2Options>): Promise<ClientOAuth2Token> {
|
||||
const options = { ...this.client.options, ...opts };
|
||||
|
||||
expects(options, 'clientId', 'clientSecret', 'accessTokenUri');
|
||||
|
||||
const body: CredentialsFlowBody = {
|
||||
grant_type: 'client_credentials',
|
||||
};
|
||||
|
||||
if (options.scopes !== undefined) {
|
||||
body.scope = sanitizeScope(options.scopes);
|
||||
}
|
||||
|
||||
const requestOptions = getRequestOptions(
|
||||
{
|
||||
url: options.accessTokenUri,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...DEFAULT_HEADERS,
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
Authorization: auth(options.clientId, options.clientSecret),
|
||||
},
|
||||
body,
|
||||
},
|
||||
options,
|
||||
);
|
||||
|
||||
const responseData = await this.client.request<ClientOAuth2TokenData>(requestOptions);
|
||||
return this.client.createToken(responseData);
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
import type { Headers } from './types';
|
||||
|
||||
export const DEFAULT_URL_BASE = 'https://example.org/';
|
||||
|
||||
/**
|
||||
* Default headers for executing OAuth 2.0 flows.
|
||||
*/
|
||||
export const DEFAULT_HEADERS: Headers = {
|
||||
Accept: 'application/json, application/x-www-form-urlencoded',
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
};
|
||||
|
||||
/**
|
||||
* Format error response types to regular strings for displaying to clients.
|
||||
*
|
||||
* Reference: http://tools.ietf.org/html/rfc6749#section-4.1.2.1
|
||||
*/
|
||||
export const ERROR_RESPONSES: Record<string, string> = {
|
||||
invalid_request: [
|
||||
'The request is missing a required parameter, includes an',
|
||||
'invalid parameter value, includes a parameter more than',
|
||||
'once, or is otherwise malformed.',
|
||||
].join(' '),
|
||||
invalid_client: [
|
||||
'Client authentication failed (e.g., unknown client, no',
|
||||
'client authentication included, or unsupported',
|
||||
'authentication method).',
|
||||
].join(' '),
|
||||
invalid_grant: [
|
||||
'The provided authorization grant (e.g., authorization',
|
||||
'code, resource owner credentials) or refresh token is',
|
||||
'invalid, expired, revoked, does not match the redirection',
|
||||
'URI used in the authorization request, or was issued to',
|
||||
'another client.',
|
||||
].join(' '),
|
||||
unauthorized_client: [
|
||||
'The client is not authorized to request an authorization',
|
||||
'code using this method.',
|
||||
].join(' '),
|
||||
unsupported_grant_type: [
|
||||
'The authorization grant type is not supported by the',
|
||||
'authorization server.',
|
||||
].join(' '),
|
||||
access_denied: ['The resource owner or authorization server denied the request.'].join(' '),
|
||||
unsupported_response_type: [
|
||||
'The authorization server does not support obtaining',
|
||||
'an authorization code using this method.',
|
||||
].join(' '),
|
||||
invalid_scope: ['The requested scope is invalid, unknown, or malformed.'].join(' '),
|
||||
server_error: [
|
||||
'The authorization server encountered an unexpected',
|
||||
'condition that prevented it from fulfilling the request.',
|
||||
'(This error code is needed because a 500 Internal Server',
|
||||
'Error HTTP status code cannot be returned to the client',
|
||||
'via an HTTP redirect.)',
|
||||
].join(' '),
|
||||
temporarily_unavailable: [
|
||||
'The authorization server is currently unable to handle',
|
||||
'the request due to a temporary overloading or maintenance',
|
||||
'of the server.',
|
||||
].join(' '),
|
||||
};
|
||||
@@ -1,2 +0,0 @@
|
||||
export { ClientOAuth2, ClientOAuth2Options, ClientOAuth2RequestObject } from './ClientOAuth2';
|
||||
export { ClientOAuth2Token, ClientOAuth2TokenData } from './ClientOAuth2Token';
|
||||
@@ -1,2 +0,0 @@
|
||||
export type Headers = Record<string, string | string[]>;
|
||||
export type Query = Record<string, string | string[]>;
|
||||
@@ -1,83 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
||||
/* eslint-disable @typescript-eslint/restrict-plus-operands */
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import type { ClientOAuth2RequestObject } from './ClientOAuth2';
|
||||
import { ERROR_RESPONSES } from './constants';
|
||||
|
||||
/**
|
||||
* Check if properties exist on an object and throw when they aren't.
|
||||
*/
|
||||
export function expects(obj: any, ...args: any[]) {
|
||||
for (let i = 1; i < args.length; i++) {
|
||||
const prop = args[i];
|
||||
if (obj[prop] === null) {
|
||||
throw new TypeError('Expected "' + prop + '" to exist');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class AuthError extends Error {
|
||||
constructor(message: string, readonly body: any, readonly code = 'EAUTH') {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull an authentication error from the response data.
|
||||
*/
|
||||
export function getAuthError(body: {
|
||||
error: string;
|
||||
error_description?: string;
|
||||
}): Error | undefined {
|
||||
const message: string | undefined =
|
||||
ERROR_RESPONSES[body.error] ?? body.error_description ?? body.error;
|
||||
|
||||
if (message) {
|
||||
return new AuthError(message, body);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure a value is a string.
|
||||
*/
|
||||
function toString(str: string | null | undefined) {
|
||||
return str === null ? '' : String(str);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize the scopes option to be a string.
|
||||
*/
|
||||
export function sanitizeScope(scopes: string[] | string): string {
|
||||
return Array.isArray(scopes) ? scopes.join(' ') : toString(scopes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create basic auth header.
|
||||
*/
|
||||
export function auth(username: string, password: string): string {
|
||||
return 'Basic ' + Buffer.from(toString(username) + ':' + toString(password)).toString('base64');
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge request options from an options object.
|
||||
*/
|
||||
export function getRequestOptions(
|
||||
{ url, method, body, query, headers }: ClientOAuth2RequestObject,
|
||||
options: any,
|
||||
): ClientOAuth2RequestObject {
|
||||
const rOptions = {
|
||||
url,
|
||||
method,
|
||||
body: { ...body, ...options.body },
|
||||
query: { ...query, ...options.query },
|
||||
headers: { ...headers, ...options.headers },
|
||||
};
|
||||
// if request authorization was overridden delete it from header
|
||||
if (rOptions.headers.Authorization === '') {
|
||||
delete rOptions.headers.Authorization;
|
||||
}
|
||||
return rOptions;
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
import nock from 'nock';
|
||||
import { ClientOAuth2, ClientOAuth2Token } from '../src';
|
||||
import * as config from './config';
|
||||
import { AuthError } from '@/utils';
|
||||
|
||||
describe('CodeFlow', () => {
|
||||
beforeAll(async () => {
|
||||
nock.disableNetConnect();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
nock.restore();
|
||||
});
|
||||
|
||||
const uri = `/auth/callback?code=${config.code}&state=${config.state}`;
|
||||
|
||||
const githubAuth = new ClientOAuth2({
|
||||
clientId: config.clientId,
|
||||
clientSecret: config.clientSecret,
|
||||
accessTokenUri: config.accessTokenUri,
|
||||
authorizationUri: config.authorizationUri,
|
||||
authorizationGrants: ['code'],
|
||||
redirectUri: config.redirectUri,
|
||||
scopes: ['notifications'],
|
||||
});
|
||||
|
||||
describe('#getUri', () => {
|
||||
it('should return a valid uri', () => {
|
||||
expect(githubAuth.code.getUri()).toEqual(
|
||||
`${config.authorizationUri}?client_id=abc&` +
|
||||
`redirect_uri=${encodeURIComponent(config.redirectUri)}&` +
|
||||
'response_type=code&state=&scope=notifications',
|
||||
);
|
||||
});
|
||||
|
||||
describe('when scopes are undefined', () => {
|
||||
it('should not include scope in the uri', () => {
|
||||
const authWithoutScopes = new ClientOAuth2({
|
||||
clientId: config.clientId,
|
||||
clientSecret: config.clientSecret,
|
||||
accessTokenUri: config.accessTokenUri,
|
||||
authorizationUri: config.authorizationUri,
|
||||
authorizationGrants: ['code'],
|
||||
redirectUri: config.redirectUri,
|
||||
});
|
||||
expect(authWithoutScopes.code.getUri()).toEqual(
|
||||
`${config.authorizationUri}?client_id=abc&` +
|
||||
`redirect_uri=${encodeURIComponent(config.redirectUri)}&` +
|
||||
'response_type=code&state=',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('should include empty scopes array as an empty string', () => {
|
||||
const authWithEmptyScopes = new ClientOAuth2({
|
||||
clientId: config.clientId,
|
||||
clientSecret: config.clientSecret,
|
||||
accessTokenUri: config.accessTokenUri,
|
||||
authorizationUri: config.authorizationUri,
|
||||
authorizationGrants: ['code'],
|
||||
redirectUri: config.redirectUri,
|
||||
scopes: [],
|
||||
});
|
||||
expect(authWithEmptyScopes.code.getUri()).toEqual(
|
||||
`${config.authorizationUri}?client_id=abc&` +
|
||||
`redirect_uri=${encodeURIComponent(config.redirectUri)}&` +
|
||||
'response_type=code&state=&scope=',
|
||||
);
|
||||
});
|
||||
|
||||
it('should include empty scopes string as an empty string', () => {
|
||||
const authWithEmptyScopes = new ClientOAuth2({
|
||||
clientId: config.clientId,
|
||||
clientSecret: config.clientSecret,
|
||||
accessTokenUri: config.accessTokenUri,
|
||||
authorizationUri: config.authorizationUri,
|
||||
authorizationGrants: ['code'],
|
||||
redirectUri: config.redirectUri,
|
||||
scopes: [],
|
||||
});
|
||||
expect(authWithEmptyScopes.code.getUri()).toEqual(
|
||||
`${config.authorizationUri}?client_id=abc&` +
|
||||
`redirect_uri=${encodeURIComponent(config.redirectUri)}&` +
|
||||
'response_type=code&state=&scope=',
|
||||
);
|
||||
});
|
||||
|
||||
describe('when authorizationUri contains query parameters', () => {
|
||||
it('should preserve query string parameters', () => {
|
||||
const authWithParams = new ClientOAuth2({
|
||||
clientId: config.clientId,
|
||||
clientSecret: config.clientSecret,
|
||||
accessTokenUri: config.accessTokenUri,
|
||||
authorizationUri: `${config.authorizationUri}?bar=qux`,
|
||||
authorizationGrants: ['code'],
|
||||
redirectUri: config.redirectUri,
|
||||
scopes: ['notifications'],
|
||||
});
|
||||
expect(authWithParams.code.getUri()).toEqual(
|
||||
`${config.authorizationUri}?bar=qux&client_id=abc&` +
|
||||
`redirect_uri=${encodeURIComponent(config.redirectUri)}&` +
|
||||
'response_type=code&state=&scope=notifications',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#getToken', () => {
|
||||
const mockTokenCall = () =>
|
||||
nock(config.baseUrl)
|
||||
.post(
|
||||
'/login/oauth/access_token',
|
||||
({ code, grant_type, redirect_uri }) =>
|
||||
code === config.code &&
|
||||
grant_type === 'authorization_code' &&
|
||||
redirect_uri === config.redirectUri,
|
||||
)
|
||||
.once()
|
||||
.reply(200, {
|
||||
access_token: config.accessToken,
|
||||
refresh_token: config.refreshToken,
|
||||
});
|
||||
|
||||
it('should request the token', async () => {
|
||||
mockTokenCall();
|
||||
const user = await githubAuth.code.getToken(uri);
|
||||
|
||||
expect(user).toBeInstanceOf(ClientOAuth2Token);
|
||||
expect(user.accessToken).toEqual(config.accessToken);
|
||||
expect(user.tokenType).toEqual('bearer');
|
||||
});
|
||||
|
||||
it('should reject with auth errors', async () => {
|
||||
let errored = false;
|
||||
|
||||
try {
|
||||
await githubAuth.code.getToken(`${config.redirectUri}?error=invalid_request`);
|
||||
} catch (err) {
|
||||
errored = true;
|
||||
expect(err).toBeInstanceOf(AuthError);
|
||||
if (err instanceof AuthError) {
|
||||
expect(err.code).toEqual('EAUTH');
|
||||
expect(err.body.error).toEqual('invalid_request');
|
||||
}
|
||||
}
|
||||
expect(errored).toEqual(true);
|
||||
});
|
||||
|
||||
describe('#sign', () => {
|
||||
it('should be able to sign a standard request object', async () => {
|
||||
mockTokenCall();
|
||||
const token = await githubAuth.code.getToken(uri);
|
||||
const requestOptions = token.sign({
|
||||
method: 'GET',
|
||||
url: 'http://api.github.com/user',
|
||||
});
|
||||
expect(requestOptions.headers?.Authorization).toEqual(`Bearer ${config.accessToken}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#refresh', () => {
|
||||
const mockRefreshCall = () =>
|
||||
nock(config.baseUrl)
|
||||
.post(
|
||||
'/login/oauth/access_token',
|
||||
({ refresh_token, grant_type }) =>
|
||||
refresh_token === config.refreshToken && grant_type === 'refresh_token',
|
||||
)
|
||||
.once()
|
||||
.reply(200, {
|
||||
access_token: config.refreshedAccessToken,
|
||||
refresh_token: config.refreshedRefreshToken,
|
||||
});
|
||||
|
||||
it('should make a request to get a new access token', async () => {
|
||||
mockTokenCall();
|
||||
const token = await githubAuth.code.getToken(uri, { state: config.state });
|
||||
expect(token.refreshToken).toEqual(config.refreshToken);
|
||||
|
||||
mockRefreshCall();
|
||||
const token1 = await token.refresh();
|
||||
expect(token1).toBeInstanceOf(ClientOAuth2Token);
|
||||
expect(token1.accessToken).toEqual(config.refreshedAccessToken);
|
||||
expect(token1.refreshToken).toEqual(config.refreshedRefreshToken);
|
||||
expect(token1.tokenType).toEqual('bearer');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,116 +0,0 @@
|
||||
import nock from 'nock';
|
||||
import { ClientOAuth2, ClientOAuth2Token } from '../src';
|
||||
import * as config from './config';
|
||||
|
||||
describe('CredentialsFlow', () => {
|
||||
beforeAll(async () => {
|
||||
nock.disableNetConnect();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
nock.restore();
|
||||
});
|
||||
|
||||
describe('#getToken', () => {
|
||||
const createAuthClient = (scopes?: string[]) =>
|
||||
new ClientOAuth2({
|
||||
clientId: config.clientId,
|
||||
clientSecret: config.clientSecret,
|
||||
accessTokenUri: config.accessTokenUri,
|
||||
authorizationGrants: ['credentials'],
|
||||
scopes,
|
||||
});
|
||||
|
||||
const mockTokenCall = (requestedScope?: string) =>
|
||||
nock(config.baseUrl)
|
||||
.post(
|
||||
'/login/oauth/access_token',
|
||||
({ scope, grant_type }) =>
|
||||
scope === requestedScope && grant_type === 'client_credentials',
|
||||
)
|
||||
.once()
|
||||
.reply(200, {
|
||||
access_token: config.accessToken,
|
||||
refresh_token: config.refreshToken,
|
||||
scope: requestedScope,
|
||||
});
|
||||
|
||||
it('should request the token', async () => {
|
||||
const authClient = createAuthClient(['notifications']);
|
||||
mockTokenCall('notifications');
|
||||
|
||||
const user = await authClient.credentials.getToken();
|
||||
|
||||
expect(user).toBeInstanceOf(ClientOAuth2Token);
|
||||
expect(user.accessToken).toEqual(config.accessToken);
|
||||
expect(user.tokenType).toEqual('bearer');
|
||||
expect(user.data.scope).toEqual('notifications');
|
||||
});
|
||||
|
||||
it('when scopes are undefined, it should not send scopes to an auth server', async () => {
|
||||
const authClient = createAuthClient();
|
||||
mockTokenCall();
|
||||
|
||||
const user = await authClient.credentials.getToken();
|
||||
expect(user).toBeInstanceOf(ClientOAuth2Token);
|
||||
expect(user.accessToken).toEqual(config.accessToken);
|
||||
expect(user.tokenType).toEqual('bearer');
|
||||
expect(user.data.scope).toEqual(undefined);
|
||||
});
|
||||
|
||||
it('when scopes is an empty array, it should send empty scope string to an auth server', async () => {
|
||||
const authClient = createAuthClient([]);
|
||||
mockTokenCall('');
|
||||
|
||||
const user = await authClient.credentials.getToken();
|
||||
expect(user).toBeInstanceOf(ClientOAuth2Token);
|
||||
expect(user.accessToken).toEqual(config.accessToken);
|
||||
expect(user.tokenType).toEqual('bearer');
|
||||
expect(user.data.scope).toEqual('');
|
||||
});
|
||||
|
||||
describe('#sign', () => {
|
||||
it('should be able to sign a standard request object', async () => {
|
||||
const authClient = createAuthClient(['notifications']);
|
||||
mockTokenCall('notifications');
|
||||
|
||||
const token = await authClient.credentials.getToken();
|
||||
const requestOptions = token.sign({
|
||||
method: 'GET',
|
||||
url: `${config.baseUrl}/test`,
|
||||
});
|
||||
|
||||
expect(requestOptions.headers?.Authorization).toEqual(`Bearer ${config.accessToken}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#refresh', () => {
|
||||
const mockRefreshCall = () =>
|
||||
nock(config.baseUrl)
|
||||
.post(
|
||||
'/login/oauth/access_token',
|
||||
({ refresh_token, grant_type }) =>
|
||||
refresh_token === config.refreshToken && grant_type === 'refresh_token',
|
||||
)
|
||||
.once()
|
||||
.reply(200, {
|
||||
access_token: config.refreshedAccessToken,
|
||||
refresh_token: config.refreshedRefreshToken,
|
||||
});
|
||||
|
||||
it('should make a request to get a new access token', async () => {
|
||||
const authClient = createAuthClient(['notifications']);
|
||||
mockTokenCall('notifications');
|
||||
|
||||
const token = await authClient.credentials.getToken();
|
||||
expect(token.accessToken).toEqual(config.accessToken);
|
||||
|
||||
mockRefreshCall();
|
||||
const token1 = await token.refresh();
|
||||
expect(token1).toBeInstanceOf(ClientOAuth2Token);
|
||||
expect(token1.accessToken).toEqual(config.refreshedAccessToken);
|
||||
expect(token1.tokenType).toEqual('bearer');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,15 +0,0 @@
|
||||
export const baseUrl = 'https://mock.auth.service';
|
||||
export const accessTokenUri = baseUrl + '/login/oauth/access_token';
|
||||
export const authorizationUri = baseUrl + '/login/oauth/authorize';
|
||||
export const redirectUri = 'http://example.com/auth/callback';
|
||||
|
||||
export const accessToken = '4430eb1615fb6127cbf828a8e403';
|
||||
export const refreshToken = 'def456token';
|
||||
export const refreshedAccessToken = 'f456okeendt';
|
||||
export const refreshedRefreshToken = 'f4f6577c0f3af456okeendt';
|
||||
|
||||
export const clientId = 'abc';
|
||||
export const clientSecret = '123';
|
||||
|
||||
export const code = 'fbe55d970377e0686746';
|
||||
export const state = '7076840850058943';
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "dist",
|
||||
"types": ["node"],
|
||||
"noEmit": false,
|
||||
"tsBuildInfoFile": "dist/build.tsbuildinfo"
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["test/**"]
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"types": ["node", "jest"],
|
||||
"composite": true,
|
||||
"noEmit": true,
|
||||
"baseUrl": "src",
|
||||
"paths": {
|
||||
"@/*": ["./*"]
|
||||
},
|
||||
"tsBuildInfoFile": "dist/typecheck.tsbuildinfo"
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user