@lightdash-tools/client 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/v1/ai-agents/discovery.d.ts +7 -2
- package/dist/api/v1/ai-agents/discovery.js +3 -6
- package/dist/api/v1/ai-agents/discovery.test.js +17 -1
- package/dist/api/v1/ai-agents/facade.d.ts +5 -0
- package/dist/api/v1/ai-agents/facade.js +5 -2
- package/dist/api/v1/charts.d.ts +19 -0
- package/dist/api/v1/charts.js +43 -1
- package/dist/api/v1/charts.test.js +45 -8
- package/dist/errors.d.ts +22 -0
- package/dist/errors.js +37 -1
- package/dist/http/http-client.binary-url.test.d.ts +4 -0
- package/dist/http/http-client.binary-url.test.js +61 -0
- package/dist/http/http-client.d.ts +23 -0
- package/dist/http/http-client.envelope.test.d.ts +4 -0
- package/dist/http/http-client.envelope.test.js +59 -0
- package/dist/http/http-client.js +155 -4
- package/dist/index.d.ts +3 -1
- package/dist/index.js +12 -3
- package/package.json +2 -2
- package/src/api/v1/ai-agents/discovery.test.ts +19 -1
- package/src/api/v1/ai-agents/discovery.ts +17 -3
- package/src/api/v1/ai-agents/facade.ts +17 -1
- package/src/api/v1/charts.test.ts +43 -1
- package/src/api/v1/charts.ts +51 -0
- package/src/errors.ts +46 -0
- package/src/http/http-client.binary-url.test.ts +88 -0
- package/src/http/http-client.envelope.test.ts +74 -0
- package/src/http/http-client.ts +198 -5
- package/src/index.ts +19 -1
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unit tests for HttpClient success-envelope harden.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
6
|
+
|
|
7
|
+
import { CONTRACT_ERROR_MESSAGE, CONTRACT_ERROR_NAME, LightdashApiError } from '../errors.js';
|
|
8
|
+
|
|
9
|
+
import { HttpClient } from './http-client.js';
|
|
10
|
+
|
|
11
|
+
import type { ResolvedLightdashClientConfig } from '../config.js';
|
|
12
|
+
import type { RateLimiter } from './rate-limiter.js';
|
|
13
|
+
import type { AxiosInstance } from 'axios';
|
|
14
|
+
|
|
15
|
+
describe('HttpClient envelope harden', () => {
|
|
16
|
+
function makeClient(requestImpl: ReturnType<typeof vi.fn>) {
|
|
17
|
+
const axiosInstance = { request: requestImpl } as unknown as AxiosInstance;
|
|
18
|
+
const rateLimiter = {
|
|
19
|
+
schedule: <T>(fn: () => Promise<T>) => fn(),
|
|
20
|
+
} as unknown as RateLimiter;
|
|
21
|
+
const config = {
|
|
22
|
+
baseUrl: 'https://app.lightdash.com',
|
|
23
|
+
timeout: 30_000,
|
|
24
|
+
retry: { maxRetries: 0 },
|
|
25
|
+
} as unknown as ResolvedLightdashClientConfig;
|
|
26
|
+
return new HttpClient(axiosInstance, rateLimiter, config);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
it('returns results for ok envelopes', async () => {
|
|
30
|
+
const client = makeClient(
|
|
31
|
+
vi.fn().mockResolvedValue({
|
|
32
|
+
status: 200,
|
|
33
|
+
data: { status: 'ok', results: { id: '1' } },
|
|
34
|
+
config: {},
|
|
35
|
+
}),
|
|
36
|
+
);
|
|
37
|
+
await expect(client.get('/x')).resolves.toEqual({ id: '1' });
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('throws LightdashApiError for error envelopes', async () => {
|
|
41
|
+
const client = makeClient(
|
|
42
|
+
vi.fn().mockResolvedValue({
|
|
43
|
+
status: 200,
|
|
44
|
+
data: {
|
|
45
|
+
status: 'error',
|
|
46
|
+
error: { name: 'Bad', statusCode: 400, message: 'nope' },
|
|
47
|
+
},
|
|
48
|
+
config: {},
|
|
49
|
+
}),
|
|
50
|
+
);
|
|
51
|
+
await expect(client.get('/x')).rejects.toMatchObject({
|
|
52
|
+
statusCode: 400,
|
|
53
|
+
error: { message: 'nope' },
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('throws ContractError for malformed 200 bodies', async () => {
|
|
58
|
+
const client = makeClient(
|
|
59
|
+
vi.fn().mockResolvedValue({
|
|
60
|
+
status: 200,
|
|
61
|
+
data: { foo: 1 },
|
|
62
|
+
config: {},
|
|
63
|
+
}),
|
|
64
|
+
);
|
|
65
|
+
await expect(client.get('/x')).rejects.toSatisfy((err: unknown) => {
|
|
66
|
+
expect(err).toBeInstanceOf(LightdashApiError);
|
|
67
|
+
const apiErr = err as LightdashApiError;
|
|
68
|
+
expect(apiErr.statusCode).toBe(502);
|
|
69
|
+
expect(apiErr.error.name).toBe(CONTRACT_ERROR_NAME);
|
|
70
|
+
expect(apiErr.error.message).toBe(CONTRACT_ERROR_MESSAGE);
|
|
71
|
+
return true;
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
});
|
package/src/http/http-client.ts
CHANGED
|
@@ -3,7 +3,17 @@
|
|
|
3
3
|
* All requests go through the rate limiter; retry applies to 5xx and network errors.
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import
|
|
6
|
+
import axios from 'axios';
|
|
7
|
+
|
|
8
|
+
import { DEFAULT_TIMEOUT } from '../config';
|
|
9
|
+
import {
|
|
10
|
+
type ApiErrorPayload,
|
|
11
|
+
BinarySizeLimitError,
|
|
12
|
+
CONTRACT_ERROR_MESSAGE,
|
|
13
|
+
CONTRACT_ERROR_NAME,
|
|
14
|
+
LightdashApiError,
|
|
15
|
+
NetworkError,
|
|
16
|
+
} from '../errors';
|
|
7
17
|
import { withRetry } from '../utils/retry';
|
|
8
18
|
|
|
9
19
|
import { type RateLimiter } from './rate-limiter';
|
|
@@ -12,6 +22,118 @@ import { isApiSuccessEnvelope, type ApiEnvelope } from './unwrap-api-success';
|
|
|
12
22
|
import type { ResolvedLightdashClientConfig } from '../config';
|
|
13
23
|
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, Method } from 'axios';
|
|
14
24
|
|
|
25
|
+
/** Default max raw bytes for chart PNG downloads (8 MiB). */
|
|
26
|
+
export const DEFAULT_BINARY_MAX_BYTES = 8 * 1024 * 1024;
|
|
27
|
+
|
|
28
|
+
export type GetBytesOptions = {
|
|
29
|
+
/** Hard cap on response body size in bytes. */
|
|
30
|
+
maxBytes?: number;
|
|
31
|
+
/** Per-request timeout override (ms). */
|
|
32
|
+
timeout?: number;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export type GetBytesResult = {
|
|
36
|
+
bytes: Buffer;
|
|
37
|
+
mimeType: string;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
function isPrivateIpv4Octets(a: number, b: number): boolean {
|
|
41
|
+
if (a === 0 || a === 10 || a === 127) {
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
if (a === 169 && b === 254) {
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
if (a === 192 && b === 168) {
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
return a === 172 && b >= 16 && b <= 31;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function isBlockedIpv6Host(host: string): boolean {
|
|
54
|
+
if (host === '::1' || host.startsWith('fe80:')) {
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
// Unique-local IPv6 (fc00::/7)
|
|
58
|
+
return host.startsWith('fc') || host.startsWith('fd');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function isAxiosMaxContentLengthError(err: unknown): boolean {
|
|
62
|
+
if (!axios.isAxiosError(err)) {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
if (typeof err.message !== 'string') {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
return err.message.includes('maxContentLength') || err.message.includes('maxBodyLength');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** True when hostname is loopback, link-local, or RFC1918 (cross-host SSRF guard). */
|
|
72
|
+
export function isBlockedBinaryHostname(hostname: string): boolean {
|
|
73
|
+
const host = hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
|
74
|
+
if (host === 'localhost' || host === 'metadata.google.internal') {
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
const ipv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
|
|
78
|
+
if (ipv4 && isPrivateIpv4Octets(Number(ipv4[1]), Number(ipv4[2]))) {
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
return isBlockedIpv6Host(host);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Reject unsafe absolute binary download URLs (exported for unit tests). */
|
|
85
|
+
export function assertSafeBinaryFetchUrl(url: string, baseUrl: string): void {
|
|
86
|
+
if (!/^https?:\/\//i.test(url)) {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
let parsed: URL;
|
|
90
|
+
try {
|
|
91
|
+
parsed = new URL(url);
|
|
92
|
+
} catch (err) {
|
|
93
|
+
throw new NetworkError(
|
|
94
|
+
'Invalid binary download URL',
|
|
95
|
+
err instanceof Error ? err : new Error(String(err)),
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
const base = new URL(baseUrl);
|
|
99
|
+
if (parsed.host === base.host && parsed.protocol === 'http:' && base.protocol === 'https:') {
|
|
100
|
+
throw new NetworkError(
|
|
101
|
+
'Binary download URL must not downgrade HTTPS to HTTP',
|
|
102
|
+
new Error(`${base.protocol} -> ${parsed.protocol}`),
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
const crossHost = parsed.host !== base.host;
|
|
106
|
+
if (!crossHost) {
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (parsed.protocol !== 'https:') {
|
|
110
|
+
throw new NetworkError(
|
|
111
|
+
'Cross-host binary download URL must use https',
|
|
112
|
+
new Error(parsed.protocol),
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
if (isBlockedBinaryHostname(parsed.hostname)) {
|
|
116
|
+
throw new NetworkError(
|
|
117
|
+
`Binary download host is not allowed: ${parsed.hostname}`,
|
|
118
|
+
new Error(parsed.hostname),
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function readApiErrorPayload(data: unknown): ApiErrorPayload['error'] | undefined {
|
|
124
|
+
if (data === null || typeof data !== 'object' || !('error' in data)) {
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
const error = (data as { error: unknown }).error;
|
|
128
|
+
if (error === null || typeof error !== 'object') {
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
131
|
+
if (typeof (error as { statusCode?: unknown }).statusCode !== 'number') {
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
return error as ApiErrorPayload['error'];
|
|
135
|
+
}
|
|
136
|
+
|
|
15
137
|
/**
|
|
16
138
|
* HTTP client that wraps Axios with rate limiting and retry.
|
|
17
139
|
*/
|
|
@@ -33,15 +155,35 @@ export class HttpClient {
|
|
|
33
155
|
const response = await this.rateLimiter.schedule(() => withRetry(doRequest, this.config.retry));
|
|
34
156
|
|
|
35
157
|
const data = response.data;
|
|
36
|
-
if (
|
|
158
|
+
if (data !== null && typeof data === 'object') {
|
|
159
|
+
const envelope = data as ApiEnvelope<T>;
|
|
160
|
+
if (isApiSuccessEnvelope(envelope)) {
|
|
161
|
+
return envelope.results;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const apiError = readApiErrorPayload(data);
|
|
166
|
+
if (apiError !== undefined) {
|
|
37
167
|
throw new LightdashApiError(
|
|
38
|
-
|
|
39
|
-
|
|
168
|
+
apiError.statusCode,
|
|
169
|
+
apiError,
|
|
40
170
|
response.config,
|
|
41
171
|
response as AxiosResponse<ApiErrorPayload>,
|
|
42
172
|
);
|
|
43
173
|
}
|
|
44
|
-
|
|
174
|
+
|
|
175
|
+
const httpStatus = response.status;
|
|
176
|
+
const contractStatus = typeof httpStatus === 'number' && httpStatus >= 400 ? httpStatus : 502;
|
|
177
|
+
throw new LightdashApiError(
|
|
178
|
+
contractStatus,
|
|
179
|
+
{
|
|
180
|
+
name: CONTRACT_ERROR_NAME,
|
|
181
|
+
statusCode: contractStatus,
|
|
182
|
+
message: CONTRACT_ERROR_MESSAGE,
|
|
183
|
+
},
|
|
184
|
+
response.config,
|
|
185
|
+
response as AxiosResponse<ApiErrorPayload>,
|
|
186
|
+
);
|
|
45
187
|
}
|
|
46
188
|
|
|
47
189
|
async get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
|
|
@@ -63,4 +205,55 @@ export class HttpClient {
|
|
|
63
205
|
async delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
|
|
64
206
|
return this.request<T>('DELETE', url, config);
|
|
65
207
|
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Fetch raw bytes (no ApiSuccess envelope unwrap). Relative URLs use the
|
|
211
|
+
* authenticated API client; absolute URLs on a different host (e.g. signed S3)
|
|
212
|
+
* are fetched without Lightdash Authorization. Cross-host fetches require https,
|
|
213
|
+
* disallow private/link-local hosts, and follow no redirects.
|
|
214
|
+
*/
|
|
215
|
+
async getBytes(url: string, options?: GetBytesOptions): Promise<GetBytesResult> {
|
|
216
|
+
const maxBytes = options?.maxBytes ?? DEFAULT_BINARY_MAX_BYTES;
|
|
217
|
+
const timeout = options?.timeout ?? this.config.timeout ?? DEFAULT_TIMEOUT;
|
|
218
|
+
assertSafeBinaryFetchUrl(url, this.config.baseUrl);
|
|
219
|
+
const binaryConfig: AxiosRequestConfig = {
|
|
220
|
+
responseType: 'arraybuffer',
|
|
221
|
+
timeout,
|
|
222
|
+
maxContentLength: maxBytes,
|
|
223
|
+
maxBodyLength: maxBytes,
|
|
224
|
+
maxRedirects: 0,
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
const doRequest = (): Promise<AxiosResponse<ArrayBuffer>> => {
|
|
228
|
+
if (/^https?:\/\//i.test(url)) {
|
|
229
|
+
const targetHost = new URL(url).host;
|
|
230
|
+
const baseHost = new URL(this.config.baseUrl).host;
|
|
231
|
+
if (targetHost !== baseHost) {
|
|
232
|
+
return axios.get<ArrayBuffer>(url, binaryConfig);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return this.axiosInstance.get<ArrayBuffer>(url, binaryConfig);
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
let response: AxiosResponse<ArrayBuffer>;
|
|
239
|
+
try {
|
|
240
|
+
// No retries: binary bodies can be multi-MiB; a 5xx would re-download the payload.
|
|
241
|
+
response = await this.rateLimiter.schedule(doRequest);
|
|
242
|
+
} catch (err) {
|
|
243
|
+
if (isAxiosMaxContentLengthError(err)) {
|
|
244
|
+
throw new BinarySizeLimitError(maxBytes);
|
|
245
|
+
}
|
|
246
|
+
throw err;
|
|
247
|
+
}
|
|
248
|
+
const bytes = Buffer.from(response.data);
|
|
249
|
+
if (bytes.byteLength > maxBytes) {
|
|
250
|
+
throw new BinarySizeLimitError(maxBytes, bytes.byteLength);
|
|
251
|
+
}
|
|
252
|
+
const rawType = response.headers['content-type'];
|
|
253
|
+
const mimeType =
|
|
254
|
+
typeof rawType === 'string'
|
|
255
|
+
? (rawType.split(';')[0]?.trim() ?? 'application/octet-stream')
|
|
256
|
+
: 'application/octet-stream';
|
|
257
|
+
return { bytes, mimeType };
|
|
258
|
+
}
|
|
66
259
|
}
|
package/src/index.ts
CHANGED
|
@@ -64,8 +64,26 @@ export type {
|
|
|
64
64
|
} from './config';
|
|
65
65
|
export { noopLogger, consoleLogger } from './utils/logger';
|
|
66
66
|
export { DEFAULT_RATE_LIMIT, DEFAULT_TIMEOUT, DEFAULT_RETRY } from './config';
|
|
67
|
-
export {
|
|
67
|
+
export {
|
|
68
|
+
LightdashApiError,
|
|
69
|
+
RateLimitError,
|
|
70
|
+
NetworkError,
|
|
71
|
+
ChartImageSizeError,
|
|
72
|
+
CONTRACT_ERROR_NAME,
|
|
73
|
+
CONTRACT_ERROR_MESSAGE,
|
|
74
|
+
} from './errors';
|
|
68
75
|
export type { ApiErrorPayload } from './errors';
|
|
76
|
+
export {
|
|
77
|
+
CHART_IMAGE_EXPORT_TIMEOUT_MS,
|
|
78
|
+
CHART_IMAGE_MAX_BYTES,
|
|
79
|
+
type ChartImagePng,
|
|
80
|
+
} from './api/v1/charts';
|
|
81
|
+
export {
|
|
82
|
+
DEFAULT_BINARY_MAX_BYTES,
|
|
83
|
+
isBlockedBinaryHostname,
|
|
84
|
+
type GetBytesOptions,
|
|
85
|
+
type GetBytesResult,
|
|
86
|
+
} from './http/http-client';
|
|
69
87
|
export { loadConfigFromEnv, mergeConfig, createBearerConfig } from './utils/env';
|
|
70
88
|
export {
|
|
71
89
|
ENV_LIGHTDASH_API_KEY,
|