Files
3c2b0816a9 feat(core): Report Internal API usage by client in telemetry (#44899)
Co-authored-by: Claude Haiku 5.5 <noreply@anthropic.com>
Co-authored-by: Uddish Verma <uddish.verma@n8n.io>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2026-12-01 13:54:59 +00:00

422 lines
11 KiB
TypeScript

import { getBrowserId, N8N_CLIENT_EDITOR_UI, N8N_CLIENT_HEADER } from '@n8n/constants';
import { assert } from '@n8n/utils/assert';
import type {
AxiosRequestConfig,
AxiosResponse,
Method,
RawAxiosRequestHeaders,
ResponseType,
} from 'axios';
import axios from 'axios';
import { jsonParse } from 'n8n-workflow';
import { BaseError } from '@n8n/errors';
import type { GenericValue, IDataObject } from 'n8n-workflow';
import type { IRestApiContext, PublicApiContext } from './types';
export const NO_NETWORK_ERROR_CODE = 999;
export const STREAM_SEPARATOR = '⧉⇋⇋➽⌑⧉§§\n';
export class MfaRequiredError extends Error {
constructor() {
super('MFA is required to access this resource. Please set up MFA in your user settings.');
this.name = 'MfaRequiredError';
}
}
export class ResponseError extends BaseError {
// The HTTP status code of response
httpStatusCode?: number;
// The error code in the response
errorCode?: number;
// The stack trace of the server
serverStackTrace?: string;
// Additional metadata from the server (e.g., EULA URL)
meta?: Record<string, unknown>;
// Additional hint from the server
hint?: string;
/**
* Creates an instance of ResponseError.
* @param {string} message The error message
* @param {number} [errorCode] The error code which can be used by frontend to identify the actual error
* @param {number} [httpStatusCode] The HTTP status code the response should have
* @param {string} [stack] The stack trace
* @param {Record<string, unknown>} [meta] Additional metadata from the server
* @param {string} [hint] Additional hint from the server
*/
constructor(
message: string,
options: {
errorCode?: number;
httpStatusCode?: number;
stack?: string;
meta?: Record<string, unknown>;
hint?: ResponseError['hint'];
} = {},
) {
super(message);
// Set explicitly, because minification renames the class.
this.name = 'ResponseError';
const { errorCode, httpStatusCode, stack, meta, hint } = options;
if (errorCode) {
this.errorCode = errorCode;
}
if (httpStatusCode) {
this.httpStatusCode = httpStatusCode;
}
if (stack) {
this.serverStackTrace = stack;
}
if (meta) {
this.meta = meta;
}
if (hint) {
this.hint = hint;
}
}
}
export type UnauthorizedHandler = (baseURL: string) => void;
let unauthorizedHandler: UnauthorizedHandler | undefined;
// Called on every 401 from request() below, with its baseURL, so non-n8n hosts can be ignored.
export function setUnauthorizedHandler(handler: UnauthorizedHandler): void {
unauthorizedHandler = handler;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const legacyParamSerializer = (params: Record<string, any>) =>
Object.keys(params)
.filter((key) => params[key] !== undefined)
.map((key) => {
if (Array.isArray(params[key])) {
return params[key].map((v: string) => `${key}[]=${encodeURIComponent(v)}`).join('&');
}
if (typeof params[key] === 'object') {
params[key] = JSON.stringify(params[key]);
}
return `${key}=${encodeURIComponent(params[key])}`;
})
.join('&');
type RequestConfig = {
method: Method;
baseURL: string;
endpoint: string;
headers?: RawAxiosRequestHeaders;
data?: GenericValue | GenericValue[];
withCredentials?: boolean;
responseType?: ResponseType;
};
/** The JSON body the server sends with an error response. */
type ErrorResponseData = {
message?: string;
code?: number;
name?: string;
stack?: string;
meta?: Record<string, unknown>;
hint?: string;
mfaRequired?: boolean;
httpStatusCode?: number;
};
/** An error body arrives as a Blob when the request asked for one. Read it as the JSON it is. */
async function readErrorResponseData(
data: ErrorResponseData | Blob | undefined,
): Promise<ErrorResponseData | undefined> {
if (!(data instanceof Blob)) return data;
try {
return jsonParse<ErrorResponseData>(await data.text());
} catch {
return undefined;
}
}
export async function request(config: RequestConfig) {
// Untyped body, as before: every caller narrows the data itself.
const response: AxiosResponse = await requestResponse(config);
return response.data;
}
/**
* The whole response, for a caller that needs the headers or a non-JSON body.
* Shares the error handling of `request`: the session-expired handler on a
* 401, and `MfaRequiredError` when the 401 asks for MFA.
*/
export async function requestResponse<T = unknown>(
config: RequestConfig,
): Promise<AxiosResponse<T>> {
const { method, baseURL, endpoint, headers, data, responseType } = config;
const options: AxiosRequestConfig = {
method,
url: endpoint,
baseURL,
headers: { ...headers },
responseType,
};
// Same-origin n8n calls only. External hosts get no extra header and no CORS preflight.
if (baseURL.startsWith('/')) {
options.headers![N8N_CLIENT_HEADER] = N8N_CLIENT_EDITOR_UI;
options.headers!['browser-id'] = getBrowserId();
}
if (
import.meta.env.NODE_ENV !== 'production' &&
!baseURL.includes('api.n8n.io') &&
!baseURL.includes('n8n.cloud')
) {
options.withCredentials = options.withCredentials ?? true;
}
if (['POST', 'PATCH', 'PUT'].includes(method)) {
options.data = data;
} else if (data) {
options.params = data;
options.paramsSerializer = legacyParamSerializer;
}
try {
return await axios.request<T>(options);
} catch (error) {
if (error.message === 'Network Error') {
throw new ResponseError("Can't connect to n8n.", {
errorCode: NO_NETWORK_ERROR_CODE,
});
}
const errorResponseData = await readErrorResponseData(error.response?.data);
if (errorResponseData?.mfaRequired === true) {
throw new MfaRequiredError();
}
// After mfaRequired: that 401 means valid-but-unenrolled, not expired.
if (error.response?.status === 401) {
unauthorizedHandler?.(baseURL);
}
if (errorResponseData?.message !== undefined) {
if (errorResponseData.name === 'NodeApiError') {
errorResponseData.httpStatusCode = error.response.status;
// The node error payload is thrown as is, so callers keep its fields. Predates the typing.
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw errorResponseData;
}
throw new ResponseError(errorResponseData.message, {
errorCode: errorResponseData.code,
httpStatusCode: error.response.status,
stack: errorResponseData.stack,
meta: errorResponseData.meta,
hint: errorResponseData.hint,
});
}
throw error;
}
}
/**
* Sends a request to the API and returns the response without extracting the data key.
* @param context Rest API context
* @param method HTTP method
* @param endpoint relative path to the API endpoint
* @param data request data
* @returns data and total count
*/
export async function getFullApiResponse<T>(
context: IRestApiContext,
method: Method,
endpoint: string,
data?: GenericValue | GenericValue[],
) {
const response = await request({
method,
baseURL: context.baseUrl,
endpoint,
headers: { 'push-ref': context.pushRef },
data,
});
return response as { count: number; data: T };
}
export async function makeRestApiRequest<T>(
context: IRestApiContext,
method: Method,
endpoint: string,
data?: GenericValue | GenericValue[],
) {
const response = await request({
method,
baseURL: context.baseUrl,
endpoint,
headers: { 'push-ref': context.pushRef },
data,
});
// All cli rest api endpoints return data wrapped in `data` key
return response.data as T;
}
export async function makePublicApiRequest<T>(
context: PublicApiContext,
method: Method,
endpoint: string,
data?: GenericValue | GenericValue[],
) {
const response = await request({
method,
baseURL: context.baseUrl,
endpoint,
headers: context.headers,
data,
});
return response as T;
}
export async function get(
baseURL: string,
endpoint: string,
params?: IDataObject,
headers?: RawAxiosRequestHeaders,
) {
return await request({ method: 'GET', baseURL, endpoint, headers, data: params });
}
export async function post(
baseURL: string,
endpoint: string,
params?: IDataObject,
headers?: RawAxiosRequestHeaders,
) {
return await request({ method: 'POST', baseURL, endpoint, headers, data: params });
}
export async function patch(
baseURL: string,
endpoint: string,
params?: IDataObject,
headers?: RawAxiosRequestHeaders,
) {
return await request({ method: 'PATCH', baseURL, endpoint, headers, data: params });
}
export async function streamRequest<T extends object>(
context: IRestApiContext,
apiEndpoint: string,
payload: object,
onChunk?: (chunk: T) => void,
onDone?: () => void,
onError?: (e: Error) => void,
separator = STREAM_SEPARATOR,
abortSignal?: AbortSignal,
): Promise<void> {
let onErrorOnce: ((e: Error) => void) | undefined = (e: Error) => {
onErrorOnce = undefined;
onError?.(e);
};
const headers: Record<string, string> = {
'browser-id': getBrowserId(),
'Content-Type': 'application/json',
};
// Same-origin n8n calls only, as in requestResponse.
if (context.baseUrl.startsWith('/')) {
headers[N8N_CLIENT_HEADER] = N8N_CLIENT_EDITOR_UI;
}
const assistantRequest: RequestInit = {
headers,
method: 'POST',
credentials: 'include',
body: JSON.stringify(payload),
signal: abortSignal,
};
try {
const response = await fetch(`${context.baseUrl}${apiEndpoint}`, assistantRequest);
if (response.body) {
// Handle the streaming response
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let buffer = '';
async function readStream() {
const { done, value } = await reader.read();
if (done) {
if (!response.ok) {
onErrorOnce?.(
new ResponseError(response.statusText, {
httpStatusCode: response.status,
}),
);
} else if (buffer.trim()) {
// The stream ended with leftover content that never parsed as JSON.
// A JSON-like fragment means the stream was cut off mid-chunk;
// anything else is a plain-text error body from an upstream
// service — surface its content instead of silently dropping it.
const leftover = buffer.trim();
const message = /^[[{]/.test(leftover) ? 'Connection lost' : leftover.slice(0, 256);
onErrorOnce?.(new Error(message));
} else {
onDone?.();
}
return;
}
const chunk = decoder.decode(value);
buffer += chunk;
const splitChunks = buffer.split(separator);
buffer = '';
for (const splitChunk of splitChunks) {
if (splitChunk) {
let data: T;
try {
data = jsonParse<T>(splitChunk, { errorMessage: 'Invalid json' });
} catch (e) {
// incomplete json. append to buffer to complete
buffer += splitChunk;
continue;
}
try {
if (response.ok) {
// Call chunk callback if request was successful
onChunk?.(data);
} else {
// Otherwise, call error callback
const message = 'message' in data ? data.message : response.statusText;
onErrorOnce?.(
new ResponseError(String(message), {
httpStatusCode: response.status,
}),
);
}
} catch (e: unknown) {
if (e instanceof Error) {
onErrorOnce?.(e);
}
}
}
}
await readStream();
}
// Start reading the stream
await readStream();
} else if (onErrorOnce) {
onErrorOnce(new Error(response.statusText));
}
} catch (e: unknown) {
assert(e instanceof Error);
onErrorOnce?.(e);
}
}