feat(core): Replace client-oauth2 with an in-repo package (#6266)
Co-authored-by: Marcus <marcus@n8n.io>
This commit is contained in:
committed by
GitHub
parent
16fade7d41
commit
a1b1f24ddf
112
packages/@n8n/client-oauth2/src/ClientOAuth2.ts
Normal file
112
packages/@n8n/client-oauth2/src/ClientOAuth2.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
/* 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,
|
||||
// Axios rejects the promise by default for all status codes 4xx.
|
||||
// We override this to reject promises only on 5xxs
|
||||
validateStatus: (status) => status < 500,
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
100
packages/@n8n/client-oauth2/src/ClientOAuth2Token.ts
Normal file
100
packages/@n8n/client-oauth2/src/ClientOAuth2Token.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
/* 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();
|
||||
}
|
||||
}
|
||||
121
packages/@n8n/client-oauth2/src/CodeFlow.ts
Normal file
121
packages/@n8n/client-oauth2/src/CodeFlow.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
52
packages/@n8n/client-oauth2/src/CredentialsFlow.ts
Normal file
52
packages/@n8n/client-oauth2/src/CredentialsFlow.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
63
packages/@n8n/client-oauth2/src/constants.ts
Normal file
63
packages/@n8n/client-oauth2/src/constants.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
/* 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(' '),
|
||||
};
|
||||
2
packages/@n8n/client-oauth2/src/index.ts
Normal file
2
packages/@n8n/client-oauth2/src/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { ClientOAuth2, ClientOAuth2Options, ClientOAuth2RequestObject } from './ClientOAuth2';
|
||||
export { ClientOAuth2Token, ClientOAuth2TokenData } from './ClientOAuth2Token';
|
||||
2
packages/@n8n/client-oauth2/src/types.ts
Normal file
2
packages/@n8n/client-oauth2/src/types.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export type Headers = Record<string, string | string[]>;
|
||||
export type Query = Record<string, string | string[]>;
|
||||
83
packages/@n8n/client-oauth2/src/utils.ts
Normal file
83
packages/@n8n/client-oauth2/src/utils.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
/* 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;
|
||||
}
|
||||
Reference in New Issue
Block a user